The client only talks to an iterator and never sees the collection internals
The client only talks to an iterator and never sees the collection internals

The idea

An iterator hands out the elements of a collection one by one without exposing its internal structure (array, linked list, tree, graph). The client asks only two questions: "is there a next one?" and "give it to me". Benefits: one collection can be traversed in different orders, several traversals do not interfere with each other, and the client code stays the same when the internals change.

The protocol in Python

In Python the pattern is built into the language: an iterable returns an iterator from __iter__(), and an iterator returns the next element from __next__() and raises StopIteration at the end. for, list(), sum() and in all use this protocol. More: the iteration protocol.

python
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1