Advertisement
Beginner Python, Iterators & the Iterator Protocol

What exception signals the end of iteration, and how does a for-loop use it internally?

Short answer

StopIteration signals that an iterator has no more values. A for-loop repeatedly calls next() on the iterator behind the scenes and automatically catches StopIteration to end the loop cleanly, without the exception propagating visibly to your code.

Save Python mock interview
Advertisement
AModel answer
StopIteration signals that an iterator has no more values. A for-loop repeatedly calls next() on the iterator behind the scenes and automatically catches StopIteration to end the loop cleanly, without the exception propagating visibly to your code.
it = iter([1, 2])
while True:
    try:
        print(next(it))
    except StopIteration:
        break
Real-world example
Understanding this lets you manually drive an iterator with next() and a try/except when you need finer control than a for-loop provides, such as peeking ahead.
Likely follow-ups
  • What happens if StopIteration is raised inside a generator function in Python 3.7+?
  • How is StopAsyncIteration different?
Related topics