Skip to content

How to Fix StopIteration in Python Generators and Iterators

DodaTech Updated 2026-06-24 2 min read

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 for loops instead of manual next() 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

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. 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

### Is StopIteration an error or a signal?

StopIteration is both. It is a signal from iterators that they are exhausted, used internally by for loops. When raised outside a for loop context and unhandled, it becomes an error that crashes the program.

What is the relationship between generators and StopIteration?

Generators raise StopIteration automatically when the function returns. This is how for loops know when to stop. Calling next() on an exhausted generator always raises StopIteration.

Why does my generator raise StopIteration on the first call?

If the generator function has no yield statements or returns immediately, it raises StopIteration on the first next() call. Make sure your generator function actually yields values.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro