SyntaxStudy
Sign Up
Python Intermediate 4 min read

The Iterator Protocol

The Iterator Protocol

An iterator must implement two methods: __iter__() (returns self) and __next__() (returns the next value or raises StopIteration).

Example
class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.n = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.n >= self.limit:
            raise StopIteration
        self.n += 1
        return self.n

for val in Counter(3):
    print(val)  # 1 2 3
Pro Tip

Implementing __iter__ on the iterator (returning self) allows it to be used directly in for loops.