September 2026
1051 pages
35h 4m
English
In Section 21.1, you learned about generators. Generators are special functions that return multiple values in succession so that iteration can be performed over them.
The following example generator generates the first n square numbers:
def square_generator(n): for i in range(1,n+1): yield i*ifor q in square_generator(3): print(q)
This sample program outputs the numbers 1, 4, and 9 on the screen. Each for loop uses the iterator protocol, so the second for loop in the example is semantically equivalent to the following program:
g = square_generator(3)try: while True: v = next(g) print(v)except StopIteration: pass
Here, a generator instance g is created first, and then the next value is read with next(g) until ...
Read now
Unlock full access