Common causes
- Calling next() on an iterator that has already been fully consumed
- Using next() without a default value on an empty iterator: next(iter([]))
- A StopIteration raised inside a generator function is converted to a RuntimeError in Python 3.7+
- Manually iterating a file or database cursor past the last record
How to fix it
- Use next() with a default to avoid the exception: next(iterator, None)
- Use a for loop instead of next() — it handles StopIteration automatically
- Check if the iterable is empty before calling next(): if items: next(iter(items))
- In generators, use return instead of raising StopIteration
Example
Traceback (most recent call last):
File "app.py", line 4, in <module>
first = next(empty_iterator)
StopIterationCalling next() on an iterator built from an empty list
Have a different error?
Paste any error message into the Error Translator to get an instant explanation.
