Iterators and generators
Generator functions and yield
Produce values on demand.
Lesson 55 of 63
Reading: about 1 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
A function containing yield returns a generator when called. Its body runs as values are requested, pausing after each yield.
Worked example
def squares(limit):
for number in range(limit):
yield number * number
items = squares(4)
print(next(items))
print(list(items))0 [1, 4, 9]
Why this works
next requests the first square. list then consumes the remaining three values. The generator does not reset after list consumes it.
Another case
def count():
yield 1
yield 2
print(sum(count()))3
Practice
Predict list(squares(3)) using a new generator.
Check the practice result
Reveal answer
It returns [0, 1, 4].
Try another case
items = squares(2); print(list(items)); print(list(items)). What prints?
Check your answer
Reveal answer
[0, 1] and then [], because the generator is exhausted after the first list().
Your progress
Reveal the check answer or reach the end to complete this lesson.