In this lesson, you will learn how to create your own custom iterator classes to define precisely how your objects behave when used in a for loop.
The Iterator Protocol
To make any object "iterable" in Python, it must follow the Iterator Protocol. This requires your class to implement two specific magic methods:
__iter__(self): This method returns the iterator object itself.__next__(self): This method returns the next item in the sequence. When there are no items left, it must raise theStopIterationexception to signal the loop to end.
Building a Custom Countdown
Imagine you want a custom object that counts down from a specific number. Instead of just storing a list, you can create a class that generates values on the fly:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
# Usage
timer = Countdown(3)
for number in timer:
print(number)
In the example above, __iter__ returns self because the class instance is the iterator. Each time the for loop asks for the next value, it calls __next__. The internal state (self.current) tracks our progress. Once the count hits zero, we raise StopIteration, which tells Python the loop is finished.
Why go through this effort?
Implementing custom iterators is much more memory-efficient than creating a standard list. If you needed to count down from one billion, a list would consume a massive amount of RAM to store all those integers at once. By using a custom iterator, you only keep the current state in memory, calculating the next value only when it is requested. This approach allows you to build sophisticated, lazy-evaluated data pipelines that remain lightweight regardless of the data size.
Key Takeaway: By implementing __iter__ and __next__ in your classes, you gain fine-grained control over your data generation while keeping your memory footprint minimal.