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.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 12 views 0 copies

Python code

23 lines
Python 3.9+
class 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

stdout
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

  1. Implement __iter__ as a generator with yield instead of manual state
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.