Python Comprehensions, Iterators and Generators · Lesson 78 of 149

Python Generators and yield

What you will learn

  • How yield turns a function into a generator
  • That generators are lazy and pause between values
  • Infinite generators and how to take part of them
  • yield from and the value of return in a generator
  • How generators save memory
  • Practical generators, and send()

1. A function that pauses

A normal function runs from start to finish and returns once. A function that contains the word yield is different. It is a generator function. Calling it does not run the body; it gives you a generator object, which is an iterator (lesson 12.4) that runs the body a piece at a time:

def count_up(n):
    for i in range(1, n + 1):
        yield i

g = count_up(3)
print(type(g).__name__)
print(next(g), next(g), next(g))
generator
1 2 3

Each next(g) runs the function until the next yield, hands out that value, and pauses right there, remembering every local variable and the exact line. The next next resumes from that spot. When the function ends, the generator raises StopIteration:

next(g)
StopIteration

Because a generator is an iterator, you use it like one: in for loops, list(...), sum(...), comprehensions and unpacking:

print(list(count_up(4)))
print(sum(count_up(100)))
print([x * x for x in count_up(4)])
[1, 2, 3, 4]
5050
[1, 4, 9, 16]
Quick check: does calling `count_up(3)` run the code in the function?

No. It only creates the generator object. The code runs when you ask for items with next or a for loop.

2. Lazy: nothing happens until you ask

A generator produces each value only when it is needed. You can see this by putting print calls in the body:

def noisy():
    print("start")
    yield 1
    print("middle")
    yield 2
    print("end")

g = noisy()
print("created")
print(next(g))
print(next(g))
created
start
1
middle
2
next(g)
end
StopIteration

Notice the order: created came first, with no start yet. The body began only at the first next, ran to yield 1, paused, and printed middle only when asked again. The last next printed end and then raised StopIteration, because the body ended.

This is called lazy evaluation: work is done on demand.

3. A generator is used up

Like every iterator, a generator can be used once:

g = count_up(3)
print(list(g))
print(list(g))
[1, 2, 3]
[]

To go through the values again, call the generator function again to get a new generator: count_up(3).

4. Infinite generators

Because values are made on demand, a generator can be endless. The usual form is a while True loop with a yield inside:

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

import itertools
print(list(itertools.islice(fib(), 10)))
print(next(x for x in fib() if x > 1000))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
1597

Never call list(fib()) on its own: it would run forever. Use islice to take a few values, or stop with a condition (lesson 12.4). This is much shorter than the Fib iterator class you wrote in lesson 12.4: Python keeps track of the state (a, b, and the position) for you.

A second example, a stream of prime numbers:

def primes():
    found = []
    n = 2
    while True:
        if all(n % p for p in found):
            found.append(n)
            yield n
        n += 1

print(list(itertools.islice(primes(), 10)))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

5. Saving memory

A list holds all its items at once. A generator holds only the state it needs to make the next one. The difference is dramatic for big data. A list of 100,000 squares on the test computer used about 800,000 bytes; the generator that makes the same numbers used 200 bytes, however many it would produce:

import sys

def squares_gen(n):
    for i in range(n):
        yield i * i

print(sys.getsizeof([x * x for x in range(100000)]))
print(sys.getsizeof(squares_gen(100000)), sys.getsizeof(squares_gen(10 ** 9)))
800984
200 200

(Exact numbers differ between computers and Python versions.) Summing a million squares with a list in the test used a peak of about 40 MB of memory, but with a generator the peak was about 1 KB and the answer was identical:

total_list = sum([x * x for x in range(1000000)])
total_gen = sum(x * x for x in range(1000000))
print(total_list == total_gen)
True

Use a generator when the data is large or endless, or when you only need part of it (for example the first match), or when you only loop once. Use a list when you need to loop several times, index, or take the length.

6. return and yield from

A return in a generator ends it, and the returned value is carried inside the StopIteration (rarely needed, but it explains yield from below):

def with_return():
    yield 1
    yield 2
    return "done"

g = with_return()
print(next(g), next(g))
try:
    next(g)
except StopIteration as e:
    print("value:", e.value)
1 2
value: done

A for loop ignores that value.

yield from hands over to another iterable, passing on all its items. It replaces a loop of yields:

def chain2(a, b):
    yield from a
    yield from b

print(list(chain2("ab", [1, 2])))
['a', 'b', 1, 2]

It is the key tool for recursive generators. Here a nested list is flattened lazily (lessons 7.5 and 11.6):

def flatten(x):
    for item in x:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

print(list(flatten([1, [2, [3, [4]], 5]])))
[1, 2, 3, 4, 5]

And a tree walk (lesson 11.6):

def tree(node):
    yield node["name"]
    for child in node.get("children", []):
        yield from tree(child)

t = {"name": "root", "children": [{"name": "a", "children": [{"name": "a1"}]}, {"name": "b"}]}
print(list(tree(t)))
['root', 'a', 'a1', 'b']

7. Practical generators

Chunks and windows

def chunks(seq, size):
    for i in range(0, len(seq), size):
        yield seq[i:i + size]

def windows(seq, n):
    for i in range(len(seq) - n + 1):
        yield seq[i:i + n]

print(list(chunks([1, 2, 3, 4, 5], 2)))
print(list(chunks("abcdefg", 3)))
print(list(windows([1, 2, 3, 4], 2)))
[[1, 2], [3, 4], [5]]
['abc', 'def', 'g']
[[1, 2], [2, 3], [3, 4]]

Chunks cut a sequence into pieces (lesson 7.3), and windows slide along it, as for moving averages.

Transforming and filtering a stream

def running_total(nums):
    total = 0
    for n in nums:
        total += n
        yield total

def numbered(lines):
    for i, line in enumerate(lines, 1):
        yield f"{i}: {line}"

def grep(lines, word):
    for line in lines:
        if word in line:
            yield line

print(list(running_total([1, 2, 3, 4])))
print(list(numbered(["a", "b"])))
print(list(grep(["apple pie", "banana", "apple tart"], "apple")))
[1, 3, 6, 10]
['1: a', '2: b']
['apple pie', 'apple tart']

Each of these takes any iterable and gives another stream, so they can be chained (lesson 12.7). A grep over a file (chapter 15) would read the file one line at a time, never loading all of it into memory.

An error stops the stream

An exception raised inside a generator reaches the code that is consuming it, and the generator is finished:

def gen_with_error():
    yield 1
    raise ValueError("bad")

try:
    for x in gen_with_error():
        print(x)
except ValueError as e:
    print("ValueError:", e)
1
ValueError: bad

8. Sending values in: send()

yield can also receive a value. Used as an expression, value = yield something pauses, and the next g.send(x) makes value equal to x:

def averager():
    total = 0
    count = 0
    avg = None
    while True:
        x = yield avg
        total += x
        count += 1
        avg = total / count

a = averager()
next(a)
print(a.send(10), a.send(20), a.send(30))
10.0 15.0 20.0
  • The first next(a) starts the generator (it runs to the first yield); you must do this before the first send.
  • Each send(x) gives a number in, and the generator yields the new running average.

This makes a generator a coroutine: a function you can talk to. g.close() stops a generator early (it raises GeneratorExit inside it). Modern Python uses async and await for most such jobs (lesson 20.5), so send is rarely needed in everyday code.

9. Generator, iterator class or list?

List Generator function Iterator class
memory all items at once one item at a time one item at a time
can loop again yes no (make a new one) no
can index and take len yes no no
length of code shortest to build with a comprehension short longest
state stored items local variables, kept for you attributes you manage

For a custom lazy sequence, a generator function is almost always simpler than an iterator class.

Worked example: reading a long log, lazily

A log has many lines, such as "INFO started" and "ERROR disk full". Find the first three errors, with their line numbers, without building any big list.

import itertools

def numbered(lines):
    for i, line in enumerate(lines, 1):
        yield i, line

def errors(pairs):
    for i, line in pairs:
        if line.startswith("ERROR"):
            yield i, line[6:]

log = [
    "INFO started", "WARN slow", "ERROR disk full", "INFO retry",
    "ERROR timeout", "INFO ok", "ERROR bad input", "ERROR crash",
]

first_three = list(itertools.islice(errors(numbered(log)), 3))
print(first_three)
print(next(errors(numbered(log))))
[(3, 'disk full'), (5, 'timeout'), (7, 'bad input')]
(3, 'disk full')
Stage Role
numbered gives (line number, text) pairs
errors keeps only the ERROR lines and cuts off the word
islice(..., 3) stops after three results

The pipeline reads the log only as far as it needs: after the third error, it stops and never looks at line 8. With a real file of millions of lines, that saves time and memory. The log lines are made up.

Common mistakes

  • Using return where you meant yield. A function that returns a list builds it all at once.
  • Using a generator twice. It is empty the second time; call the function again.
  • Calling list(...) on an infinite generator.
  • Expecting the body to run when the generator is created. It runs on the first next.
  • Indexing a generator or taking its len. Convert to a list first (if it is finite).
  • Forgetting the first next(a) before send.

Key takeaways

  • A function with yield is a generator function: calling it gives a generator (an iterator) that runs on demand and pauses at each yield.
  • Generators are lazy, use almost no memory, can be infinite, and are used up after one pass.
  • yield from passes on every item of another iterable, which suits recursion and chaining.
  • Write generators for large or endless data, for streams you filter and transform, and for custom sequences.
  • send() lets a generator receive values, which makes it a coroutine; the first call must be next.

Practice

1. Write a generator evens(limit) that yields the even numbers below limit.

Show answer
def evens(limit):
    n = 0
    while n < limit:
        yield n
        n += 2

2. What is type(count_up(3)).__name__, and has the code of the function run?

Show answer

'generator'. No: calling it only creates the generator; the code runs when you ask for values.

3. Why does list(g) give [] the second time?

Show answer

A generator is an iterator, and it is used up after one pass. Call the generator function again for a fresh one.

4. Rewrite this with yield from: for x in a: yield x.

Show answer

yield from a.

5. Take the first 5 squares from an endless generator squares().

Show answer

list(itertools.islice(squares(), 5)).

6. When would you choose a list instead of a generator?

Show answer

When you need to loop over the data more than once, index into it, take its length, or when it is small and simplicity matters.