← Back to Error Guide
StopIteration

How to Fix StopIteration

Understanding and resolving StopIteration in Python

What is StopIteration?

The StopIteration error happens when you try to get the next item from an iterator that has no more items left.

Common Causes

Common causes of this error...

How to Fix

Wrong Code

# Code that causes the error
numbers = iter([1, 2, 3])
print(next(numbers))
print(next(numbers))
print(next(numbers))
print(next(numbers))

Correct Code

# Fixed code
numbers = iter([1, 2, 3])
try:
    while True:
        print(next(numbers))
except StopIteration:
    pass

More Python Error Guides