Overview
Produce values one at a time with yield — handle huge or endless sequences without building them in memory.
- yield vs return
- Iterating a generator
- list() to collect values
- Generator expressions
Short Course
A function containing yield becomes a generator: each yield hands
back one value and pauses until the next one is requested. Nothing is
computed until you iterate.
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x) # 3, 2, 1
list(countdown(3)) # -> [3, 2, 1]
squares = (x * x for x in range(5)) # generator expression
Task
Write a generator fib(n) that yields the first n Fibonacci numbers,
starting 0, 1, 1, 2, 3, ….
Test Suites
Pending
Stdout