← Python from Scratch Lesson 67 of 78 · 10 XP

Iterators and generators

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Why can for go through strings, lists, dictionaries and range alike? Because they are all iterable: they have a magic method __iter__ that returns an iterator — an object with a __next__ method that hands out the next item.

it = iter([10, 20])
next(it)     # 10
next(it)     # 20
next(it)     # StopIteration — out of items; this is where for stops

Your own iterable class:

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

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

The same thing is written much more briefly as a generator — a function with yield. It "freezes" at each yield and continues from the same place on the next request:

def countdown(start):
    while start > 0:
        yield start
        start -= 1

Generators hand out values one at a time and don't keep them all in memory. That's why you can go through even huge files this way.

Task. Write a generator evens(n) that yields the even numbers from 0 to n inclusive.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.