Lesson 13 of 14 · 12 min

Iterators and generators

A for loop works with anything iterable: lists, strings, ranges, dictionaries. Behind the scenes it asks the object for one value at a time.

A generator is the simplest way to make your own iterable. It looks like a function, but uses yield instead of return:

def even_numbers(limit):
    n = 0
    while n < limit:
        yield n
        n += 2

for x in even_numbers(7):
    print(x)          # 0, 2, 4, 6

Each yield hands one value to the loop and pauses the function. When the loop asks for the next value, the function carries on from where it paused.

Why bother?

Generators produce values lazily, one at a time, so they use almost no memory, even for huge or endless sequences:

def naturals():
    n = 1
    while True:      # never ends, and that is fine
        yield n
        n += 1

You take only what you need, for example with itertools.islice(naturals(), 5).

Generator expressions

Like a list comprehension, but in round brackets: (n * n for n in range(10)). Passed straight to sum, max or any, it never builds the full list.

Your task

  1. countdown(n): a generator yielding n, n - 1, ..., 1.
  2. fibonacci(): an endless generator of Fibonacci numbers: 0, 1, 1, 2, 3, 5...
  3. chunks(items, size): yields consecutive lists of size items (the last may be shorter).
  4. total_even_squares(limit): the sum of n * n for every even n below limit, using a generator expression.
main.py
def countdown(n):
    pass


def fibonacci():
    pass


def chunks(items, size):
    pass


def total_even_squares(limit):
    pass


print(list(countdown(5)))

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…