Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python StopIteration and StopAsyncIteration

Reference for Python StopIteration and StopAsyncIteration: how iterators signal the end, next() defaults, the value attribute and the generator RuntimeError rule.

StopIteration is how an iterator says "I have nothing more to give". When you call next() on an exhausted iterator, it raises StopIteration. A for loop calls next() for you and treats this exception as the signal to end quietly, so you normally never see it.

StopAsyncIteration is the same idea for asynchronous iterators: the __anext__() awaitable raises it, and async for stops cleanly. Both inherit directly from Exception.

Python
it = iter([1, 2])
next(it)   # 1
next(it)   # 2
next(it)   # StopIteration

Try it

Python Exhausting an iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Custom iterators and the generator rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
try:
    value = next(iterator)
except StopIteration as stop:
    result = stop.value        # generator's return value, or None

value = next(iterator, default)   # no exception
Name Description
value On StopIteration: the value returned by a generator (return x), or the first argument given to the exception; None by default.

Raises when: next() is called on an exhausted iterator; __next__() signals the end; __anext__() raises StopAsyncIteration for async iterators.

Usage notes

  • Prefer for loops. They handle the end for you. Use next(it, default) when you want one item or a fallback instead of an exception.
  • Iterables versus iterators. A list is iterable but not an iterator, so next([1, 2]) raises TypeError. Call iter() first.
  • Exhausted means exhausted. Once an iterator raised StopIteration, it should keep raising it. Generators and file objects cannot be restarted; create a new one.
  • Generators: return value ends a generator, and the value travels in StopIteration.value. yield from hands that value to the outer generator.
  • PEP 479 rule. If a StopIteration is raised inside a generator body and not caught, Python turns it into RuntimeError: generator raised StopIteration. End a generator with return instead of raise StopIteration.
  • Same for coroutines and async generators: a stray StopIteration becomes RuntimeError, and StopAsyncIteration raised in an async generator does too.
  • Writing __next__: raise StopIteration with no arguments when finished. Do not use it to report errors.
  • First match idiom. next(x for x in items if condition(x)) raises StopIteration when nothing matches; pass a default to avoid that.
  • Don't catch it casually. A bare except Exception swallows it and can hide a loop that ended early.