Iterators and generators
Produce values on demand with yield.
An iterable can produce an iterator through iter(). Each call to next() advances the iterator. A for loop handles the end automatically when the iterator raises StopIteration.
Calling a function containing yield creates a generator. Its body runs until it yields a value, then pauses. The next iteration resumes from that point. This is useful when the full sequence would be large or when you only need its first few values.
The call creates a generator. Its body has yet to run.
Try it yourself
Write a generator for the first four positive multiples of 3. Print the first value with next() and the remaining values as a list.
Target output
3
[6, 9, 12]Show a hint
Reuse the loop shape and yield number * 3 instead of a square.
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
def multiples(limit):
for number in range(1, limit + 1):
yield number * 3
sequence = multiples(4)
print(next(sequence))
print(list(sequence))