Codzy

Iterators

An iterator is an object that hands out the items of a sequence one by one. The for loop uses them behind the scenes: iter() creates the iterator and next() gives the next item.

To make your own class iterable, write two methods: __iter__, which returns the iterator (often self), and __next__, which returns the next value. When there is nothing left, __next__ raises StopIteration and the loop stops.

letters = iter(["a", "b", "c"])
print(next(letters))
print(next(letters))

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

for n in Countdown(3):
    print(n)

Start the lesson