Understand StopIteration, iterator exhaustion, and generator return values.
What You Will Learn
When a generator finishes, it signals completion with StopIteration; a return statement can attach a value to that exception. A for loop hides this exception during normal iteration. Raising StopIteration directly inside generator code is converted into RuntimeError under modern Python semantics.
A for loop does not expose the return value; manual next() or yield from delegation can observe it.
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 count_then_finish():
yield 1
yield 2
return 'finished'
iterator = count_then_finish()
print(next(iterator))
print(next(iterator))
try:
next(iterator)
except StopIteration as completion:
print(completion.value)
How the Example Works
- The function count_then_finish defines reusable behavior; its body executes when it is called, not when it is declared.
- The variable iterator holds the result of count_then_finish(). Later lines use that value or inspect how it changes.
- The control-flow block demonstrates when each value is processed or when cleanup and exception handling take effect.
- 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:
1
2
finished
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
Write a generator that yields two items and returns a descriptive completion value.
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
- Manually raising StopIteration inside a generator body instead of returning normally.
- Overlooking this documented constraint: raising StopIteration directly inside generator code is converted into RuntimeError under modern Python semantics.
Key Takeaways
- Understand StopIteration, iterator exhaustion, and generator return values.
- When a generator finishes, it signals completion with StopIteration; a return statement can attach a value to that exception.
- A for loop does not expose the return value; manual next() or yield from delegation can observe it.