python runtime_error ai_generated true

StopIteration:

ID: python/stopiteration-next-on-empty-generator

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-04-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active

Root Cause

Calling next() on a generator or iterator that has no more items, without a default value.

generic

中文

在没有默认值的情况下对没有更多项的生成器或迭代器调用 next()。

Workarounds

  1. 95% success Provide default value to next()
    item = next(generator, None)
  2. 90% success Use for loop instead of next()
    for item in generator:
        process(item)

Dead Ends

Common approaches that don't work:

  1. Catching StopIteration with a bare except 60% fail

    Bare except catches all exceptions, potentially hiding other bugs.

  2. Using list(iterator) without checking length 40% fail

    list() consumes the iterator but does not handle empty case gracefully.