In this lesson, you will learn how Python’s for loops actually traverse data by implementing the two methods that define the Iterator Protocol: __iter__ and __next__.
The Iterator Protocol
Whenever you write for item in my_collection:, Python is performing a "handshake" with that object. For an object to be iterable, it must satisfy two requirements:
- The
__iter__method: This method must return an iterator object. Usually, for a simple custom class, you just returnself. - The
__next__method: This method defines how to get the next item. When there are no items left, it must raise theStopIterationexception, which signals theforloop to stop.
Seeing it in Action
Imagine we want to build a custom object that counts down from a number. We don't just store data; we provide the mechanism for traversal.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
# Using our custom iterator
timer = Countdown(3)
for count in timer:
print(count)
How it works
When the for loop starts, it calls __iter__(). Then, it repeatedly calls __next__() on the object returned by __iter__.
In our example, the first call to __next__ returns 3, the next returns 2, then 1. On the fourth call, the if statement triggers, raising StopIteration. Python catches this exception internally, gracefully ending the loop.
This protocol is why you can iterate over lists, ranges, and even custom file readers using the exact same syntax. You are essentially building a state machine that remembers where it is in the sequence and knows exactly when to quit.
Key Takeaway: The Iterator Protocol relies on __iter__ to initialize the traversal and __next__ to yield values until a StopIteration exception signals that the sequence is exhausted.