Lingua-e
← Errors
Python

StopIteration: What It Means and How to Fix It

Error reference

StopIteration

Language

Python

Severity

Low

When it happens

StopIteration is raised by an iterator's __next__() method to signal that there are no more items to produce.

Potential fixes

Pass a default value as the second argument to next(): next(it, None). Use for loops instead of manual next() calls for straightforward iteration. If you need to iterate an iterator multiple times, convert it to a list first with list(iterator).

Related errors

Deep dive

StopIteration is raised by an iterator's __next__() method to signal that there are no more items to produce. It is the normal termination signal for iterators and is automatically caught by for loops, but it will propagate as an error if you call next() manually without a default.

Why it happens

  • Calling next() on an iterator that has already been fully consumed.
  • Using next() inside a generator function, which causes the generator itself to stop.
  • Manually iterating with next() instead of using a for loop, without providing a default value.
  • Consuming a generator or iterator in one place and then trying to iterate it again (iterators cannot be rewound).

Potential fixes

Pass a default value as the second argument to next(): next(it, None). Use for loops instead of manual next() calls for straightforward iteration. If you need to iterate an iterator multiple times, convert it to a list first with list(iterator).

Examples

Python

Code that triggers the error

numbers = iter([1, 2, 3])

print(next(numbers))  # 1
print(next(numbers))  # 2
print(next(numbers))  # 3
print(next(numbers))  # iterator is exhausted

Error output

1
2
3
Traceback (most recent call last):
  File "app.py", line 6, in <module>
    print(next(numbers))
StopIteration

Fixed code

numbers = iter([1, 2, 3])

# Use a default value to avoid the exception
value = next(numbers, None)
while value is not None:
    print(value)
    value = next(numbers, None)

# Or simply iterate with a for loop:
for n in [1, 2, 3]:
    print(n)

Practice in English

How would you explain a StopIteration to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free