How to Create an Iterator Class with Dunder Methods in Python

A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

20 lines
Python 3.9+
class Counter:
    def __init__(self, start=0, end=5):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        value = self.current
        self.current += 1
        return value


if __name__ == "__main__":
    counter = Counter(1, 5)
    for num in counter:
        print(num)

Output

stdout
1
2
3
4

How it works

The __iter__ method returns self, making the object its own iterator, which is required for any iterator. __next__ contains the loop logic: it checks the current value against the end, raises StopIteration when exhausted, otherwise returns the current value and increments it. The class is also an iterable, so it works directly in a for loop. This pattern is flexible and can be extended with custom logic or additional state.

Common mistakes

  • Forgetting to increment the current value inside __next__
  • Not raising StopIteration, causing an infinite loop
  • Missing __iter__ that returns self, making `for` loops fail

Variations

  1. Use a generator function with `yield` for a simpler iterator
  2. Inherit from collections.abc.Iterator to enforce the protocol

Real-world use cases

  • Custom sequence generators for paginated API clients that fetch data chunk by chunk.
  • Lazy-loaded file parsers that yield records one at a time without loading all into memory.
  • Stateful iterators for game loops or simulation steps that maintain internal counters.

Sponsored

Run this sample

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

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.