StopIteration
PythonINFOCommonControl FlowHIGH confidence

Iterator has no more items

What this means

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.

Why it happens
  1. 1A `for` loop naturally consumes an iterator until it is exhausted.
  2. 2Manually calling `next()` on an iterator that has no more items.
  3. 3A generator function finishes its execution or uses `return`.
How to reproduce

This exception is triggered when `next()` is called on an iterator that has already been fully consumed.

trigger — this will error
trigger — this will error
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.

Use a `for` loop to handle iteration
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.

Provide a default value to `next()`
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.

Code examples
Triggerpython
it = iter([1])
next(it)  # 1
next(it)  # StopIteration
Handle with next() defaultpython
it = iter([1])
val = next(it, None)  # returns None instead of raising StopIteration
Avoid with for looppython
for item in my_iterable:
    process(item)
# StopIteration caught automatically
What not to do

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.

Sources
Official documentation ↗

cpython/Objects/exceptions.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors