BehavioralPythonverifiedVerified

Iterator Pattern in Python

Provides a way to sequentially access elements of a collection without exposing its underlying representation.

How to Implement the Iterator Pattern in Python

1Step 1: Implement the collection as a Python iterable using __iter__

class NumberRange:
    """A range of numbers with a custom step, implementing the iterator protocol."""

    def __init__(self, start: int, end: int, step: int = 1) -> None:
        self._start = start
        self._end = end
        self._step = step

    def __iter__(self) -> "RangeIterator":
        return RangeIterator(self._start, self._end, self._step)

2Step 2: Implement the iterator with __next__ and StopIteration

class RangeIterator:
    def __init__(self, start: int, end: int, step: int) -> None:
        self._current = start
        self._end = end
        self._step = step

    def __iter__(self) -> "RangeIterator":
        return self

    def __next__(self) -> int:
        if self._current > self._end:
            raise StopIteration
        value = self._current
        self._current += self._step
        return value

3Step 3: Traverse the range using Python's for loop

number_range = NumberRange(1, 10, 2)
for num in number_range:
    print(num)  # 1, 3, 5, 7, 9


# Alternatively, use a generator for the same effect
def number_range_gen(start: int, end: int, step: int = 1):
    current = start
    while current <= end:
        yield current
        current += step


for num in number_range_gen(1, 10, 2):
    print(num)

Iterator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Iterator Pattern in the Real World

Think of a TV remote control. Whether your playlist is on a Blu-ray disc, a streaming service, or a USB drive, you use the same next and previous buttons to cycle through content. The remote (iterator interface) abstracts away the completely different internal mechanisms each media source uses to retrieve the next item.