python
runtime_error
ai_generated
true
StopIteration
ID: python/stopiteration
90%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
next() called on exhausted iterator. Since PEP 479, StopIteration inside generator becomes RuntimeError.
genericWorkarounds
-
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
-
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:
-
Catch StopIteration inside the generator
75% fail
PEP 479 converts this to RuntimeError — catching won't help
-
Reset the iterator by reassigning
70% fail
Iterators can't be reset — need to create a new one
Error Chain
Frequently confused with: