Course contentsShow
← Python
Lesson 265 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Signaling Completion with StopIteration

You will implement the StopIteration exception to gracefully inform Python loops when a custom iterator has no more data to provide.

Signaling Completion with StopIteration

In this lesson, you will learn how to gracefully tell Python's for loops that your custom iterator has finished providing data by raising the StopIteration exception.

The Iterator Protocol's Exit Strategy

When you build a custom iterator, Python needs a way to know exactly when to stop calling the __next__() method. If you don't provide a signal, the loop might try to access data that doesn't exist, leading to errors or infinite loops. The formal way to handle this is by raising a StopIteration exception.

When Python’s iteration machinery sees StopIteration being raised inside your __next__ method, it catches the exception silently and tells the loop to terminate immediately.

Seeing it in Action

Imagine we are creating a countdown iterator that counts down to zero. Once it hits zero, we need to stop.

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < 0:
            # Signal the loop to stop
            raise StopIteration
        
        value = self.current
        self.current -= 1
        return value

# Usage
for number in Countdown(2):
    print(number)

In this example, the Countdown class keeps track of its state. Every time __next__ is called, we check if self.current is less than zero. If it is, we raise StopIteration. Python catches this behind the scenes, realizes there is no more data to process, and the for loop exits cleanly without crashing.

Why use this instead of returning None?

You might wonder why we don't just return None when we are done. If we returned None, the loop would interpret None as a valid piece of data and print it! By using StopIteration, we provide a specific, reserved signal that indicates the end of the sequence rather than a valid data value. This keeps your custom iterators robust and compatible with all standard Python iteration tools.

Key Takeaway: Raising StopIteration is the standard, signal-based mechanism to inform Python that your iterator has no more elements to yield, allowing loops to terminate cleanly.