Python StopIteration Exception
Example
A StopIteration occurs if you call next() when there are no more items:
fruits = iter(["apple", "banana"])
print(next(fruits))
print(next(fruits))
print(next(fruits))
Try it Yourself »
Definition and Usage
The StopIteration exception occurs when the next() function is called on an iterator that has no more items.
A for loop catches StopIteration for you. This is how the loop knows when to stop.
Tip: Give next() a default value, like next(fruits, "none"), to get that value instead of the error.
Exception Handling
Example
Handling the StopIteration in a try...except statement:
fruits = iter(["apple", "banana"])
print(next(fruits))
print(next(fruits))
try:
print(next(fruits))
except StopIteration:
print("There are no more items")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.