Python Comprehensions, Iterators and Generators · Lesson 79 of 149

Python Generator Expressions

What you will learn

  • What a generator expression is, and how it differs from a list comprehension
  • Passing one directly to sum, max, any, all, join and others
  • Early stopping with any and all
  • The syntax rule about brackets
  • A trap: when each part is evaluated
  • When a list is the better choice

1. Comprehension in round brackets

A generator expression looks exactly like a list comprehension, but with round brackets instead of square ones. Instead of building a list, it creates a generator (lesson 12.5) that makes its values one at a time, on demand:

nums = [1, 2, 3, 4, 5, 6]

squares = (n * n for n in nums)
print(type(squares).__name__)
print(next(squares), next(squares))
print(list(squares))
print(list(squares))
generator
1 4
[9, 16, 25, 36]
[]
List comprehension Generator expression
brackets [ ... ] ( ... )
result a list, built at once a generator, built item by item
memory all items almost nothing
can loop again yes no, used up after one pass
indexing, len yes no

It supports everything a list comprehension does: filters, conditional expressions and several for clauses (lessons 12.1 and 12.2):

pairs = ((x, y) for x in range(3) for y in range(3) if x < y)
print(list(pairs))
[(0, 1), (0, 2), (1, 2)]
Quick check: what is the difference between `[n for n in nums]` and `(n for n in nums)`?

The first builds a list of all the items at once. The second makes a generator that produces them one at a time.

2. Feeding functions directly

Many functions take one iterable and use it once: sum, max, min, sorted, tuple, set, dict, any, all and str.join. For these, a generator expression is ideal, because no list is built just to be thrown away:

print(sum(n * n for n in nums))
print(max(n * n for n in nums))
print(sorted(n % 3 for n in nums))
print(tuple(n for n in nums if n % 2))
print("-".join(str(n) for n in nums))
print(dict((n, n * n) for n in range(3)))
91
36
[0, 0, 1, 1, 2, 2]
(1, 3, 5)
1-2-3-4-5-6
{0: 0, 1: 1, 2: 4}

The bracket rule

When the generator expression is the only argument of a call, you do not need extra brackets: sum(n * n for n in nums). The call's own brackets are enough. If there are other arguments, you must add brackets of its own:

def two(a, b):
    return a + b

print(max((n for n in nums), default=0))
print(max((n for n in []), default=0))
print(sum((n for n in nums), 100))
6
0
121

Without the inner brackets, two(n for n in [1], 2) is a SyntaxError: Generator expression must be parenthesized.

Counting

sum(1 for ...) is the standard way to count how many items fit a condition, without building a list:

print(sum(1 for n in nums if n % 2 == 0))
print(sum(1 for c in "banana" if c == "a"))
3
3

3. any and all stop early

any and all stop as soon as the answer is known (lesson 5.6). With a generator expression, the items after that point are never even calculated. A function with a print shows this:

def check(n):
    print("checking", n)
    return n > 2

print(any(check(n) for n in [1, 2, 3, 4, 5]))
checking 1
checking 2
checking 3
True

any stopped at 3, the first True, so 4 and 5 were never checked. Compare a list comprehension, which does all the work first:

print([check(n) for n in [1, 3]])
checking 1
checking 3
[False, True]

This matters when the test is expensive, such as reading a file or asking a server. all(check(n) for n in [5, 1, 9]) stops at the first False too.

4. The default max with an empty generator

max and min fail on an empty input unless you give default= (lesson 3.3):

print(max((n for n in nums if n > 100), default="none"))
none

For that reason, pass default= whenever a filter might remove every item.

5. A trap: what is evaluated when

A generator expression is lazy, but not everything is delayed. The rule:

  • The first iterable (the one after the first in) is looked at immediately, when the generator is created.
  • Everything else (the expression, conditions, other loops) is evaluated later, as items are requested.
lst = [1, 2, 3]
g = (x * 10 for x in lst)
lst.append(4)
print(list(g))
[10, 20, 30, 40]

The generator holds an iterator over the same list, so the later append is seen (lesson 12.4). But rebinding the name afterwards makes no difference, because the first iterable was already taken:

lst = [1, 2, 3]
g = (x * 10 for x in lst)
lst = [100]
print(list(g))
[10, 20, 30]

And a free variable in the expression is read when each item is made, not when the generator is created:

mult = 2
g = (x * mult for x in [1, 2, 3])
mult = 10
print(list(g))
[10, 20, 30]

It used mult = 10, the value at the time of consumption. This is the same "late binding" you met in closures (lesson 11.10). The safe habits: consume a generator expression soon after creating it, and do not change the variables it depends on in between.

6. Used up after one pass

A generator expression, like any generator, cannot be reused. This silent bug is common:

g = (x for x in range(3))
print(list(g))
print(list(g))
[0, 1, 2]
[]

If you need the items twice, build a list (square brackets) once and use it again. A frequent form of this mistake is a function that both sums and counts a generator, where the second use sees nothing.

7. List or generator expression?

Situation Choose
passing to sum, max, any, all, join (one pass) generator expression
a huge or endless source generator expression
you may stop early (any, next) generator expression
you need the result more than once, or to index it or take len list
the data is small and clarity matters either, a list is simplest
str.join on many pieces a list is a little faster

The last row may surprise you: str.join needs the whole sequence in memory anyway, so it converts a generator to a list first. In a test on one computer, "".join([str(i) for i in range(100)]) was faster than the same with a generator expression. For small data the difference is tiny, so choose for readability, and measure (lesson 18.5) before optimising.

8. Pipelines of generator expressions

Each generator expression can take another one as its source, forming a pipeline in which every item passes through all stages one at a time, with no big lists in between:

lines = ["a,1", "b,2", "c,3"]

rows = (line.split(",") for line in lines)
named = ((name, int(num)) for name, num in rows)
big = (pair for pair in named if pair[1] > 1)

print(list(big))
[('b', 2), ('c', 3)]

Nothing happens until list(big) asks for items. Then each line is split, converted and tested in turn. Lesson 12.7 builds on this idea.

Other tools accept generators happily, for example the statistics module:

import statistics
print(statistics.mean(n for n in nums))
print(statistics.median(n for n in [5, 1, 3]))
3.5
3

9. Memory, measured

Summing a million squares shows the difference. On the test computer, the list version peaked at about 40 MB of memory and the generator at about 1 KB, with the same answer:

big_list = sum([x * x for x in range(1000000)])
big_gen = sum(x * x for x in range(1000000))
print(big_list == big_gen)
True

(The memory figures are from a measurement with tracemalloc on one computer; yours will differ, but the gap will be large.)

Worked example: statistics without lists

A list of orders holds (customer, amount) pairs. Answer several questions with generator expressions, never building a list of amounts.

orders = [("Rina", 40), ("Sam", 25), ("Rina", 60), ("Lee", 10), ("Sam", 80)]

total = sum(amount for _, amount in orders)
biggest = max(amount for _, amount in orders)
count_big = sum(1 for _, amount in orders if amount >= 40)
has_small = any(amount < 20 for _, amount in orders)
all_positive = all(amount > 0 for _, amount in orders)
first_big = next((c for c, amount in orders if amount > 50), None)
rina_total = sum(a for c, a in orders if c == "Rina")
names = ", ".join(sorted({c for c, _ in orders}))

print(total, biggest, count_big)
print(has_small, all_positive, first_big)
print(rina_total, names)
print(round(total / len(orders), 1))
215 80 3
True True Rina
100 Lee, Rina, Sam
43.0
Question Tool
total and biggest sum and max of a generator
how many are big sum(1 for ...)
any small, all positive any and all (stop early)
the first big order's customer next(..., None)
the customers, sorted and unique a set comprehension inside sorted

None of these builds a list of the amounts. The customers and amounts are made up.

Common mistakes

  • Using a generator expression twice. It is empty the second time.
  • Forgetting the inner brackets when the generator is not the only argument.
  • Changing the variables that a not-yet-consumed generator uses.
  • Expecting len(...), indexing or slicing to work on a generator.
  • Using a generator where a list is faster or needed (str.join, repeated passes).
  • Forgetting default= for max and min over a filtered generator.

Key takeaways

  • (expression for item in iterable) makes a generator: lazy, tiny in memory, and used up after one pass.
  • Pass it straight to sum, max, min, sorted, any, all, tuple, set, dict and join; the call's own brackets are enough when it is the only argument.
  • any and all with a generator stop early, so later items are never calculated.
  • The first iterable is taken at creation; other variables are read when items are produced.
  • Use a list when you need the result more than once, an index, a length, or maximum speed for small data.

Practice

1. Add up the squares of 1 to 10 with a generator expression.

Show answer

sum(n * n for n in range(1, 11)) gives 385.

2. Count the words longer than 3 letters in words without building a list.

Show answer

sum(1 for w in words if len(w) > 3).

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

Show answer

A generator is used up after one pass. Build a list with [...] if you need the items twice.

4. Which brackets does sum(...) need around n for n in nums?

Show answer

None extra: when the generator expression is the only argument, the call's own brackets are enough, as in sum(n for n in nums).

5. Why is any(slow_check(x) for x in items) better than any([slow_check(x) for x in items])?

Show answer

With the generator, any stops at the first true result and never calls slow_check on the remaining items. The list version calls it on every item first.

6. What does list(g) show if mult changes between creating g = (x * mult for x in [1, 2]) and consuming it?

Show answer

It uses the new value of mult, because the variable is read when each item is produced, not when the generator is created.