ProjectStack
python

StopIteration

StopIteration signals that an iterator has no more items to produce. Calling next() on an exhausted iterator raises this. Inside a generator, it's normal, but leaking outside a generator function can crash your code in Python 3.7+.

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

  1. Use next() with a default to avoid the exception: next(iterator, None)
  2. Use a for loop instead of next() — it handles StopIteration automatically
  3. Check if the iterable is empty before calling next(): if items: next(iter(items))
  4. 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) StopIteration

Calling 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.