__iter__ and __next__

say it: “DUN-der IT-er and DUN-der NEKST” /ˈdʌndər ˈɪtər ənd ˈdʌndər ˈnɛkst/

Methods that make your own class work in a for loop.

What do __iter__ and __next__ do?

These two methods make your own class loopable: __iter__ hands back the object that does the looping, and __next__ gives the next item or raises StopIteration when there are none left.

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

print(list(Countdown(3)))  # [3, 2, 1]

Level: Freelancer · More Python terms at this level

Updated