StopIteration in Python — What It Means and How to Fix It
What Python's StopIteration exception means and how to resolve it.
Published October 28, 2026
StopIteration is raised by next() when an iterator has no more items. For loops handle it automatically.
What it means and why it happens
You see it when calling next() on an exhausted iterator or generator, or from generators returning in older code.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
StopIteration
Practical examples
Code that triggers it
it = iter([1])
next(it)
next(it)The fix
it = iter([1])
print(next(it, None))
print(next(it, None))Use for loops
for x in [1, 2, 3]:
print(x) # StopIteration handled for youCommon mistakes
- Calling next() without a default.
- Reusing exhausted generators.
- Raising StopIteration inside generators (RuntimeError in 3.7+).
Key takeaways
- StopIteration: StopIteration is raised by next() when an iterator has no more items.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
How do I avoid it?
Use for loops or pass a default to next().
How do I find which line caused StopIteration?
The error message and stack trace show the file and line; start there and work backwards.