How to Implement Iterator Protocol on a Custom Class in Python
Create a custom iterable class by defining the __iter__ and __next__ methods, enabling use in for loops and list conversions.
Python code
23 linesclass Countdown:
"""Iterator that counts down from start to 0."""
def __init__(self, start):
self.start = 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
if __name__ == "__main__":
for number in Countdown(5):
print(number, end=" ")
print()
print(list(Countdown(3)))
Output
5 4 3 2 1 0
[3, 2, 1, 0]
How it works
The iterator protocol requires two methods: __iter__, which returns the iterator object itself, and __next__, which returns the next value or raises StopIteration when exhausted. The class maintains its own current state, decrementing it each call. This makes the object its own iterator, so each for loop or list() call uses the same object state. Running it multiple times requires re-initializing the instance.
Common mistakes
- Forgetting to raise StopIteration, causing infinite loops
- Resetting state inside __next__ instead of __init__
- Not returning self from __iter__
Variations
- Implement __iter__ as a generator with yield instead of manual state
- Make __iter__ return a separate iterator class to support multiple independent traversals
Real-world use cases
- Building a paginated API client that iterates over response pages lazily.
- Creating a custom file parser that yields records one at a time from a stream.
- Implementing a retry iterator that yields attempts until success or max retries.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.