NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle+89 views

Можно ли бесконечно вызывать `next()` у генератора и что произойдёт после его исчерпания?

Practice

AI answer

You can call next() as many times as you like, but once the generator is exhausted, each subsequent call without a default value raises StopIteration. The generator is then considered finished and does not start over.

g = iter([1])
next(g)  # 1
next(g)  # StopIteration
next(g)  # StopIteration again

next(g, None)  # None instead of an exception

If the generator is infinite and continues to yield values, StopIteration will not occur.