One thing at a time.
Produce values lazily instead of building a whole collection up front.
01 The idea
A generator function uses yield to produce a value and suspend execution. The next request resumes from that point. This is useful for pipelines and streams because you can process items incrementally without storing every result at once.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def countdown(start):
while start > 0:
yield start
start -= 1
ticks = countdown(3)
print(next(ticks))
print(list(ticks))
print(list(ticks))3 [2, 1] []
03 Under the hood
- 1
Calling countdown() creates a generator object. The body does not execute until a value is requested.
- 2
next() runs the body to its next yield. Converting the rest to a list consumes the remaining values.
- 3
Generators are iterators that are consumed. After exhaustion, another list(ticks) is empty. Create a new generator if you need another pass. A generator expression offers a compact lazy transformation using parentheses.
04 Your turn, builder
Write a generator that yields the squares of 1 through 3 and print its values as a list.
Reveal one possible solution +
def squares():
for number in range(1, 4):
yield number ** 2
print(list(squares()))05 Check your signal
What happens to a generator after all its values have been consumed?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.