A StopIteration exception occurs when an iterator has no more items to return. It is commonly encountered when using the next() function to manually retrieve values from an iterator after all elements have been exhausted.
numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output
1
2
3
Traceback (most recent call last):
File "<main.py>", line 7, in <module>
StopIteration
Explanation: iterator successfully returns the first three values. When next() is called again, there are no more items available, so Python raises a StopIteration exception.
Common Causes
A StopIteration exception is raised whenever an iterator reaches the end of its data. This typically happens when iterators are used manually with the next() function.
1. Iterator Exhaustion: Once all elements of an iterable have been consumed, any additional call to next() raises StopIteration.
my_set = {1, 2, 3}
iterator = iter(my_set)
while True:
item = next(iterator)
print(item)
Output
1
2
3
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
StopIteration
Explanation: iterator returns all elements from the set. After the last element is returned, Python raises StopIteration because no more values are available.
2. Manual Iteration Over a Sequence: The same issue can occur while manually iterating through strings, tuples, lists, or any iterable object.
text = "Hello"
iterator = iter(text)
while True:
char = next(iterator)
print(char)
Output
H
e
l
l
o
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
StopIteration
Explanation: Each character is returned one at a time. After the final character is processed, the iterator reaches the end and raises StopIteration.
Handling StopIteration
1. for Loop: to avoid StopIteration errors is to use a for loop. Python automatically handles the exception internally.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Output
1 2 3 4 5
Explanation: for loop automatically catches the StopIteration exception and stops the iteration when all elements have been processed.
2. try-except with next(): If you need to use next() manually, handle the exception using a try-except block.
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
while True:
try:
value = next(iterator)
print(value)
except StopIteration:
break
Output
1 2 3 4 5
Explanation: When the iterator reaches the end, next() raises StopIteration. The exception is caught and the loop exits gracefully.
3. next() with a Default Value: next() function allows a default value to be returned instead of raising StopIteration.
numbers = [1, 2]
iterator = iter(numbers)
print(next(iterator, "End"))
print(next(iterator, "End"))
print(next(iterator, "End"))
Output
1 2 End
Explanation: When the iterator is exhausted, next() returns the specified default value ("End") instead of raising an exception.
4. Generators: Generators automatically handle iteration and make working with iterators simpler.
def generate_numbers():
yield 1
yield 2
yield 3
yield 4
yield 5
for num in generate_numbers():
print(num)
Output
1 2 3 4 5
Explanation: generator yields values one at a time. The for loop automatically handles the end of the generator without exposing the StopIteration exception.