StopIteration

StopIteration is a built-in exception that signals the end of an iteration when an iterator has no more items to return.

Python uses it internally to manage iteration processes, particularly in for loops and comprehensions.

StopIteration Occurs When

  • A for loop finishes iterating over an iterator
  • The next() function is called on an iterator that has no more items

If StopIteration occurs as a normal part of executing a loop, then you won’t see the exception. This is because Python handles it internally.

StopIteration Can Be Used When

You can use StopIteration when creating custom iterators. You’ll raise this exception in the .__next__() method to signal the end of the iteration.

StopIteration Examples

An example of when the exception appears:

Python
>>> numbers_iterator = iter([1, 2, 3])

>>> next(numbers_iterator)
1
>>> next(numbers_iterator)
2
>>> next(numbers_iterator)
3
>>> next(numbers_iterator)
Traceback (most recent call last):
    ...
StopIteration

An example of how to handle the exception:

Python
>>> numbers_iterator = iter([1, 2, 3])
>>> while True:
...     try:
...         number = next(numbers_iterator)
...         print(number)
...     except StopIteration:
...         break
...
1
2
3

An example of when to raise the exception:

Python custom_iterator.py
class CustomIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        result = self.data[self.index]
        self.index += 1
        return result

# Usage
iterator = CustomIterator([1, 2, 3])
for item in iterator:
    print(item)  # Output: 1 2 3

Tutorial

Iterators and Iterables in Python: Run Efficient Iterations

In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 26, 2025 • Reviewed by Martin Breuss