Skip to content

StopIteration from manual next() call

Quick summary

You called next() on an iterator that has no more items — Python raises StopIteration, which crashes your program if uncaught.

Why this happens

  • You called next() more times than the iterator has items without checking for exhaustion

  • A generator function was fully consumed in a previous loop, and you called next() again on the same generator

  • You used next() without a default value inside a context that does not handle StopIteration (like a plain expression)

Minimal example

✗ Broken code
it = iter([1, 2, 3])
print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3
print(next(it))  # StopIteration!
✓ Fixed code
it = iter([1, 2, 3])
while True:
    val = next(it, None)
    if val is None:
        break
    print(val)  # prints 1, 2, 3

Using next(it, None) returns None when the iterator is exhausted, letting you check and break instead of raising StopIteration.

How to diagnose

  • Add a default argument to next(it, default) so it returns the default instead of raising StopIteration

  • Use a for loop or list(it) to consume the iterator safely instead of manual next() calls

  • Wrap the next() call in a try/except StopIteration to handle exhaustion explicitly

How to fix

  • Pass a sentinel default to next(it, None) so it returns None (or another default) when the iterator is exhausted

  • Rewrite the manual next() loop as a for loop that naturally handles iteration completion

  • Catch StopIteration with try/except and break or return to exit the consuming logic cleanly

How to prevent

  • Always use next(it, default) with a default value when you are not certain the iterator has more items

  • Prefer for loops over manual next() calls for most iteration patterns to avoid StopIteration entirely

Related Resources

Related Glossary

Related Lessons

  • Iterators

    Learn about iterators and generators.

← Back to language