StopIteration
StopIteration
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
next(it) # raises StopIteration
StopIterationWhat causes this error
The `next()` built-in was called on an exhausted iterator without providing a default value, or StopIteration propagated unexpectedly from within a generator function.
How to fix it
Use `next(iterator, default_value)` to provide a fallback. Use for loops instead of manual next() calls when possible. In generators, catch StopIteration explicitly from nested iterators.
Code that causes this error
it = iter([1, 2]) next(it) next(it) next(it) # raises StopIteration
Fixed code
it = iter([1, 2]) val = next(it, None) # 1 val = next(it, None) # 2 val = next(it, None) # None (no error)
About StopIteration
StopIteration is raised by the `__next__()` method of an iterator to signal that there are no more items. This is not typically an error in normal code — it is the standard mechanism by which for loops and other iteration constructs know when to stop. However, StopIteration can become a real bug when using `next()` manually without providing a default value, or when it accidentally propagates out of a generator (which, as of Python 3.7, is converted to a RuntimeError due to PEP 479).
If you call `next(iterator)` and the iterator is exhausted, StopIteration is raised. To avoid this, always provide a default value: `next(iterator, default)`. In generator functions, an accidental StopIteration from a nested call will be caught and converted to RuntimeError, which helps prevent subtle bugs where generators silently stop producing values.
Common scenarios
Infinite recursion from missing or incorrect base cases
Modifying dictionaries or sets during iteration
Calling generators or coroutines in unsupported ways
Using asyncio event loops incorrectly or attempting to nest them