Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

StopIteration — iterator exhaustion

StopIteration signals iterator exhaustion during next(). Its value attribute can carry a generator's return value. Ending a generator with return is different from allowing an explicitly raised StopIteration to escape its code.

Version: Python 3.14; repository image, production runtime not attested

Syntax

StopIteration(*args)
try:
    item = next(iterator)
except StopIteration as exc:
    result = exc.value

StopIteration signals that an iterator has no more items. next(iterator) calls iterator.__next__(); on exhaustion it raises the exception unless a default was supplied.

next(iterator, default) returns the next item if one is available. Only when the iterator is exhausted does it return default instead of raising StopIteration. Choose a default distinguishable from valid items. When handling the exception manually, keep the try block limited to retrieving an item.

StopIteration(value) stores its argument in value, which defaults to None. Ending a generator with return result exposes result as StopIteration.value, not as another item from yield.

Inside a generator, use return, not raise StopIteration. If a directly or indirectly raised StopIteration escapes its code, Python converts it to RuntimeError, retaining the original exception as its cause. Asynchronous iteration ends with the separate StopAsyncIteration.

Examples

def numbers():
    yield 7
    return 99

iterator = numbers()
print(next(iterator))
try:
    next(iterator)
except StopIteration as exc:
    print(type(exc).__name__, exc.value)
print(next(iterator, "END"))

Result

7
StopIteration 99
END

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources