How to Fix StopIteration in Python Generators and Iterators
In this tutorial, you'll learn about How to Fix StopIteration in Python Generators and Iterators. We cover key concepts, practical examples, and best practices.
Python raises StopIteration when the next() function is called on an iterator that has already been exhausted and no default value is provided.
The Wrong Way
numbers = iter([1, 2, 3])
print(next(numbers))
print(next(numbers))
print(next(numbers))
print(next(numbers)) # no more items
This produces:
1
2
3
Traceback (most recent call last):
File "script.py", line 6, in <module>
print(next(numbers))
StopIteration
The Right Way
Provide a default value to next():
numbers = iter([1, 2, 3])
print(next(numbers, "End"))
print(next(numbers, "End"))
print(next(numbers, "End"))
print(next(numbers, "End"))
Output:
1
2
3
End
Step-by-Step Fix
1. Use for loop instead of manual next()
numbers = iter([1, 2, 3])
for num in numbers:
print(num)
# No StopIteration -- for loop handles it
2. Catch StopIteration explicitly
numbers = iter([1, 2, 3])
while True:
try:
num = next(numbers)
print(num)
except StopIteration:
print("No more items")
break
Output:
1
2
3
No more items
3. Use next() with sentinel value in a generator
def read_until_empty():
while True:
value = yield
if value is None:
break
print(f"Got: {value}")
gen = read_until_empty()
next(gen) # prime the generator
gen.send("Hello")
gen.send("World")
gen.send(None) # triggers StopIteration
4. Safely consume an iterator
def safe_next(iterator, default=None):
try:
return next(iterator)
except StopIteration:
return default
items = iter([])
print(safe_next(items, "Empty"))
Output:
Empty
Prevention Tips
- Use
forloops instead of manualnext()calls. - Always provide a default value to
next()when you must use it. - Use
list(<a href="/design-patterns/iterator/">iterator</a>)to consume the entire iterator safely. - Use
itertools.islice()for partial consumption. - Wrap custom iterator code in try-except StopIteration blocks.
Common Mistakes with stopiteration
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro