How to Fix Generator Already Exhausted in Python
In this tutorial, you'll learn about How to Fix Generator Already Exhausted in Python. We cover key concepts, practical examples, and best practices.
A Python generator can only be iterated once. After it is exhausted, subsequent attempts to iterate produce no results without raising an error -- silently returning nothing.
The Wrong Way
def count_up_to(n):
for i in range(n):
yield i
gen = count_up_to(3)
# First iteration works
for num in gen:
print(num)
# Second iteration produces nothing
for num in gen:
print(num) # nothing prints
Output:
0
1
2
(No output from the second loop.)
The Right Way
Create a new generator for each iteration, or convert to a list:
def count_up_to(n):
for i in range(n):
yield i
n = 3
# First iteration
for num in count_up_to(n):
print(num)
# Second iteration -- create a fresh generator
for num in count_up_to(n):
print(num)
Output:
0
1
2
0
1
2
Step-by-Step Fix
1. Convert to a list for multiple iterations
def count_up_to(n):
for i in range(n):
yield i
gen = count_up_to(3)
numbers = list(gen)
# Use numbers as many times as needed
print(numbers)
print(numbers)
2. Create a generator function for reuse
def get_items():
yield from ["apple", "banana", "cherry"]
# Each call creates a new generator
for item in get_items():
print(item)
for item in get_items():
print(item.upper())
3. Use itertools.tee for multiple iterators
import itertools
gen = count_up_to(3)
gen1, gen2 = itertools.tee(gen, 2)
print(list(gen1))
print(list(gen2))
4. Check if a generator is exhausted
def safe_iterate(gen):
try:
first = next(gen)
# Yield first item, then the rest
yield first
yield from gen
except StopIteration:
return # generator was already exhausted
gen = count_up_to(3)
list(gen) # exhaust it
for item in safe_iterate(gen):
print(item) # prints nothing -- generator was already exhausted
Prevention Tips
- Never reuse a generator -- create a fresh one when needed.
- Convert to a list if you need to iterate multiple times.
- Wrap generator creation in a function that returns a new generator each time.
- Use
itertools.tee()when you need two independent iterators. - Add comments when a generator is consumed in one pass.
Common Mistakes with generator exhausted
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
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