Sub topic 9
Generator expressions: the lazy alternative
This chapter assumes you can write a list comprehension with a filter, and that you know what for, range, and sum do. A generator expression looks almost the same as a list comprehension, but it behaves differently in memory and in how many times you can use it.
Brackets versus parentheses
A list comprehension uses square brackets and builds the whole list immediately. A generator expression uses parentheses and builds nothing up front. It produces one item each time something asks for the next one.
squares_list = [n * n for n in range(5)]
squares_gen = (n * n for n in range(5))
print(squares_list) # [0, 1, 4, 9, 16]
print(squares_gen) # <generator object <genexpr> at 0x...>Printing the generator shows only its type, because no squares have been computed yet. The same for and if clauses work in both forms. Only the delimiters differ.
Avoiding a big temporary list
Functions such as sum, min, max, any, all, and sorted accept any iterable. If you only need a single result, a generator expression saves you from building a list that you throw away right after.
total = sum(n * n for n in range(1_000_000))
print(total) # 333332833333500000Here the call's own parentheses also serve as the generator expression's parentheses, so you don't write a second pair. The memory use stays small however large the range is. The list version, sum([n * n for n in range(1_000_000)]), would first store a million integers.
Stopping early
Because items are produced on demand, a consumer that stops early also stops the computation. any and all stop at the first deciding item.
numbers = [3, 8, 12, 5]
print(any(n > 10 for n in numbers)) # TrueThe generator is asked for 3, then 8, then 12. At 12 the condition is true, so any returns without looking at 5. You can also pull a single item with next, and pass a default to use when nothing matches:
numbers = [3, 8, 12, 5]
first_even = next((n for n in numbers if n % 2 == 0), None)
print(first_even) # 8Here the generator expression needs its own parentheses, because it is not the only argument to next.
A generator can be used only once
A list can be read as many times as you like. A generator is a stream. Once its items have been consumed, it is empty.
gen = (n * n for n in range(3))
print(list(gen)) # [0, 1, 4]
print(list(gen)) # []The second list(gen) returns an empty list and raises no error. This is the most common surprise with generators. If you need to loop over the results twice, use a list, or create a new generator each time.
A generator also has no length and no indexing. len(gen) and gen[0] both raise TypeError.
Choosing between the two
| Need | Use |
|---|---|
| Pass results to `sum`, `max`, `any`, `all`, or `sorted` once | Generator expression |
| Loop over the results one time, and the data may be large | Generator expression |
| Read results more than once, index them, or call `len` | List comprehension |
| See all the values while debugging | List comprehension |
A generator is not always faster. For small inputs, a list comprehension is often as fast or slightly faster, because it avoids the overhead of resuming a generator for each item. The reason to choose a generator is memory and early stopping, so don't use one for speed alone.
Lazy means errors appear late
Since the work happens only when items are requested, an error in the expression does not appear where you wrote the generator. It appears where you consume it.
data = [1, 2, 0]
inverses = (1 / n for n in data) # no error yet
print(next(inverses)) # 1.0
print(next(inverses)) # 0.5A third next(inverses) would raise ZeroDivisionError. A traceback pointing at the consuming line can be confusing when the generator was defined much earlier. Keep the definition and its use close together.
Exercise
You write evens = (n for n in range(10) if n % 2 == 0), then run print(sum(evens)) followed by print(sum(evens)). What does each line print, and why?
Show answer
The first prints 20 (0 + 2 + 4 + 6 + 8). The second prints 0. The first sum consumes every item from the generator, so the second sum finds it empty and returns the starting value 0. Use a list comprehension, or build the generator again, if you need the items twice.
Exercise
Which is a better fit for finding out whether any line in a very large list of strings contains the word "error": any(["error" in line for line in lines]) or any("error" in line for line in lines)?
Show answer
The second, with no square brackets. It is a generator expression, so any stops at the first matching line. The bracketed version first builds a full list of booleans for every line, then passes it to any.