Sub topic 2
Generator Functions: Iterators with `yield`
Assume you know Python functions, loops, collections, and try/except. A generator function is a function containing yield. Calling it returns a generator object, which is an iterator. The function body does not run until the generator receives a request for its next value.
Generator functions: iterators with `yield`
An iterator produces values one at a time. A generator function creates an iterator without requiring you to write __iter__, __next__, and StopIteration yourself.
def countdown(start):
while start > 0:
yield start
start -= 1
for number in countdown(3):
print(number)The loop prints 3, 2, and 1. Each yield supplies one value and preserves the function's local variables.
How a generator runs
A generator moves through three stages:
The first next() runs from the beginning to the first yield. A later next() resumes immediately after that yield. When the function returns or reaches the end, Python raises StopIteration, which a for loop handles automatically.
def demo():
print("start")
yield 1
print("middle")
yield 2
print("end")
gen = demo()
print("created")
print(next(gen))
print(next(gen))
try:
next(gen)
except StopIteration:
print("stopped")The output shows that "start" is printed only during the first next(), not when demo() is called.
> callout note > A generator is single-use. After it raises StopIteration, create a new generator if you need another pass.
Generator expressions
A generator expression is a compact generator form. It uses parentheses rather than list brackets:
squares = (number * number for number in range(4))
print(next(squares)) # 0
print(list(squares)) # [1, 4, 9]The first value is consumed by next(), so it does not appear in the later list.
Lazy evaluation and memory savings
Lazy evaluation means computing a value only when it is requested. A list stores every result immediately, while a generator stores its current position and produces the next result on demand. This can reduce memory use when processing large inputs.
Generators can also represent unbounded streams, but consumers must stop explicitly:
from itertools import islice
def numbers():
value = 0
while True:
yield value
value += 1
print(list(islice(numbers(), 5))) # [0, 1, 2, 3, 4]Exercise
What does next(countdown(2)) return, and why does it not return both values?
Show answer
It returns 2. Each next() request retrieves only the next yielded value; a later request would retrieve 1.