Iterator has no more items
Raised by an iterator's `__next__()` method to signal that there are no further items. This is not typically an error; it's a normal signal used to terminate loops.
- 1A `for` loop naturally consumes an iterator until it is exhausted.
- 2Manually calling `next()` on an iterator that has no more items.
- 3A generator function finishes its execution or uses `return`.
This exception is triggered when `next()` is called on an iterator that has already been fully consumed.
my_list = [1] my_iterator = iter(my_list) print(next(my_iterator)) # Prints 1 print(next(my_iterator)) # Raises StopIteration
expected output
1 Traceback (most recent call last): File "<stdin>", line 4, in <module> StopIteration
Fix 1
Use a `for` loop to handle iteration
WHEN You want to process all items from an iterator.
my_list = [1, 2]
# The for loop automatically handles the StopIteration signal
for item in my_list:
print(item)
Why this works
Python's `for` loop is built to work with iterators. It calls `next()` on each iteration and automatically catches the `StopIteration` to end the loop gracefully.
Fix 2
Provide a default value to `next()`
WHEN You are manually calling `next()` and want to get a specific value when the iterator is exhausted instead of an exception.
my_list = [1] my_iterator = iter(my_list) print(next(my_iterator)) # The second argument is the default value to return print(next(my_iterator, "end"))
Why this works
The `next()` built-in function can take a second argument, which will be returned if the iterator is exhausted, preventing the `StopIteration` from being raised.
it = iter([1]) next(it) # 1 next(it) # StopIteration
it = iter([1]) val = next(it, None) # returns None instead of raising StopIteration
for item in my_iterable:
process(item)
# StopIteration caught automatically✕ Catching `StopIteration` in regular application logic
This exception is part of Python's internal iteration protocol. Catching it can interfere with the normal behavior of `for` loops and other iteration constructs.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev