See exactly when a generator function pauses and resumes at each yield.
What You Will Learn
Calling a function containing yield returns a generator object without running its body immediately. Each next() resumes execution until the next yield; local variables keep their values between pauses. When the function finishes, next() raises StopIteration. This is different from return, which ends the function.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
def countdown(start):
print("Generator started")
while start > 0:
yield start
start -= 1
numbers = countdown(3)
print("Created generator")
print(next(numbers))
print(next(numbers))
print(next(numbers))
How the Example Works
- The function countdown defines reusable behavior; its body executes when it is called, not when it is declared.
- The variable numbers holds the result of countdown(3). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
Created generator
Generator started
3
2
1
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Add a print immediately after yield and explain the exact order of messages.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Expecting the first print inside a generator to run when you merely call countdown().
- Assuming yield returns the entire sequence in one operation like return.
Key Takeaways
- See exactly when a generator function pauses and resumes at each yield.
- Calling a function containing yield returns a generator object without running its body immediately.
- Apply this operation only after checking the assumptions and input conditions shown in the example.