Use yield when a function should produce values one at a time instead of computing every result immediately. Calling such a generator function returns a generator object; execution begins when iteration requests a value. section 11.4
Each yield returns its value to the caller and suspends the function at that point. A later next call resumes execution after the yield, preserving local variables and parameters in the generator’s single stack frame. section 11.15 section 11.19
Keep these generator behaviors in mind:
- A for loop repeatedly requests values until the generator reaches the end of its function, when StopIteration occurs automatically. section 11.4
- Use yield to continue producing values; use return to exit the generator completely. Do not explicitly raise StopIteration inside a generator. section 11.17
- Use retained state for incremental calculations, such as measuring the time since the previous iteration. section 11.19
- Prefer a generator function when it expresses iteration more simply than a class implementing the iterator protocol. section 11.23
def foo():
yield 1
yield 2
yield 3
This minimal generator yields three values in sequence, pausing after each one. section 11.4
g = foo()
for one_item in g:
print(one_item)
Iteration drives the generator: each loop pass requests the next value and prints it. section 11.4









