Lesson 2 of 5 · Advanced Python · 2 min read · Updated

Generators

Producing values one at a time with yield — for huge or endless sequences.

Writing an iterator class takes a dozen lines. A generator does the same with a normal function that uses yield instead of return. Each yield hands out one value and pauses the function right there until the next value is asked for.

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

for x in countdown(3):
    print(x)

gen = countdown(2)
print(next(gen), next(gen))
Output
3
2
1
2 1

Generator expressions

python
print(sum(n * n for n in range(1, 1_000_001)))

marks = [72, 45, 91, 38]
print(sum(m for m in marks if m >= 50))
print(any(m < 40 for m in marks), all(m > 30 for m in marks))
Output
333333833333500000
163
True True

Round brackets instead of square ones make a generator instead of a list. The sum of a million squares above never builds a million-item list: each square is made, added and forgotten. any() and all() even stop early, as soon as the answer is known.

Sequences that never end

python
from itertools import islice

def evens():
    n = 0
    while True:
        yield n
        n += 2

print(list(islice(evens(), 5)))
Output
[0, 2, 4, 6, 8]

Note

An endless generator is safe because nothing is computed until asked for. itertools.islice takes just the first few. The standard itertools module has many more building blocks: count, cycle, chain, groupby.

What is the difference between [x * 2 for x in data] and (x * 2 for x in data)?

Try this now

  1. Write a generator fibonacci() that yields Fibonacci numbers forever, and print the first 15 with islice.
  2. Write a generator that reads a file and yields only the lines that are not blank.

Create a free account to save your progress, or sign in.