Generators
Produce values on demand and explain how yield preserves state.
On this page
The concept
A generator function contains yield. Calling it returns a generator iterator instead of running the entire body immediately. Each request resumes execution until the next yield, preserving local state between requests. This can avoid building a large intermediate list.
A generator expression uses parentheses and produces values lazily. A list comprehension uses brackets and constructs its list immediately. yield from delegates production to another iterable; the solution uses it for the even-number range. Both forms still create one-pass iterators.
Worked example
def countdown(start):
while start > 0:
yield start
start -= 1
for number in countdown(3):
print(number)
squares = (number**2 for number in range(1, 6))
print(next(squares))
print(sum(squares))
print(list(squares))Trace the result
- countdown yields a value, then decreases its local state before the next yield.
- The first next consumes the square of 1.
- sum consumes the remaining squares, so a subsequent list call is empty.
3
2
1
1
54
[]Line-by-line walkthrough
Lines 1–4: def countdown(start):
Define the function countdown with input names start. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Lines 2–4: while start > 0:
Check start > 0 before each pass. The loop runs only while the condition is truthy. Identify the state update or exit that makes it stop; its body may execute zero times.
Line 3: yield start
Yield start to the generator caller and suspend here. The next request resumes the saved execution state.
Line 4: start -= 1
Update the current target using start -= 1. Trace its value before and after this line; later statements see the updated state.
Lines 7–8: for number in countdown(3):
Obtain each item from countdown(3) and bind it to number before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Line 8: print(number)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 9: squares = (number**2 for number in range(1, 6))
Evaluate (number ** 2 for number in range(1, 6)), then bind or update squares with the result. Read the source iteration, optional filter, and produced expression as separate steps. Assignment itself does not imply a deep copy.
Line 10: print(next(squares))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 11: print(sum(squares))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 12: print(list(squares))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Laziness does not mean an iterator can be reused indefinitely. Create a new generator for a new pass.