Python › Iterators & the Iterator Protocol
What exception signals the end of iteration, and how does a for-loop use it internally?
BeginnerAnswer
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:
breakReal-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.