Python developers often encounter the StopIteration exception when working with iterators. This error occurs when an iterator has no more items to return, typically when the next() function is called after exhaustion.
What Causes StopIteration?
In Python, iterators raise StopIteration to signal that iteration is complete. This is a natural part of the iterator protocol. For example:
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
print(next(iterator)) # Raises StopIteration
How to Handle It?
You can catch the exception using a try-except block:
while True:
try:
item = next(iterator)
# process item
except StopIteration:
break
Alternatively, use a for loop which handles the exception automatically.
Key Takeaway
StopIteration is not necessarily an error—it's a mechanism to end iteration. Understanding it helps you write better Python code and debug iterator-related issues.
This article was adapted from a Python tutorial video.