python runtime_error ai_generated true

StopIteration

ID: python/stopiteration

Also available as: JSON · Markdown
90%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

next() called on exhausted iterator. Since PEP 479, StopIteration inside generator becomes RuntimeError.

generic

Workarounds

  1. 95% success Use next(iter, default) to provide a default value for exhausted iterators
    val = next(my_iter, None)

    Sources: https://docs.python.org/3/library/functions.html#next

  2. 90% success Convert to list first if you need multiple passes, or recreate the iterator
    items = list(my_iterator)  # Materialize once
    # Now you can iterate multiple times:
    for item in items: pass
    for item in items: pass

    Sources: https://docs.python.org/3/library/functions.html#list

Dead Ends

Common approaches that don't work:

  1. Catch StopIteration inside the generator 75% fail

    PEP 479 converts this to RuntimeError — catching won't help

  2. Reset the iterator by reassigning 70% fail

    Iterators can't be reset — need to create a new one

Error Chain

Frequently confused with: