Sub topic 8
Lazy evaluation and memory savings
This chapter assumes you can write a generator function and a generator expression, and that you know how for loops call next() on an iterator. Earlier chapters covered both. Here we look at what they buy you: lower memory use, earlier results, and streams of unbounded length. We also look at where laziness surprises people.
What lazy evaluation means
An eager computation does all of its work up front and returns a finished result. A lazy computation returns a recipe and does each piece of work only when a consumer asks for the next value.
A list comprehension is eager. It builds every element before you see the first one. A generator expression is lazy. It stores its position and the code to run, and it produces one value per next() call.
eager = [x * x for x in range(5)] # all five squares exist now
lazy = (x * x for x in range(5)) # no square has been computed yet
print(eager) # [0, 1, 4, 9, 16]
print(next(lazy)) # 0, computed only now
print(next(lazy)) # 1The lazy object holds one suspended frame. It does not hold the results. Memory use therefore depends on how many values are alive at once, not on how many values the sequence contains.
Measuring the difference
The quickest comparison uses sys.getsizeof.
import sys
squares_list = [x * x for x in range(1_000_000)]
squares_gen = (x * x for x in range(1_000_000))
print(sys.getsizeof(squares_list)) # roughly 8,000,000 bytes
print(sys.getsizeof(squares_gen)) # roughly 100-200 bytesThe exact numbers vary by Python version and platform. The gap does not: the list size grows with the element count, and the generator size stays constant.
tracemalloc is in the standard library. It records allocations made by Python and reports the peak.
import tracemalloc
def peak_kib(func):
tracemalloc.start()
func()
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak / 1024
def eager():
return sum([x * x for x in range(1_000_000)])
def lazy():
return sum(x * x for x in range(1_000_000))
print(f"eager peak: {peak_kib(eager):,.0f} KiB")
print(f"lazy peak: {peak_kib(lazy):,.0f} KiB")Both functions return the same number. The eager version needs tens of thousands of KiB at its peak because the whole list and its integer objects exist at the same moment. The lazy version stays at a few KiB, because sum takes one value, adds it, and lets the value go before asking for the next.
Passing a generator expression as the only argument to a function lets you drop the extra parentheses. That is why sum(x * x for x in ...) is valid.
Where the savings come from
The lazy loop in the diagram is the whole mechanism. Each value exists only between the moment the generator yields it and the moment the consumer is done with it. If the consumer does not keep a reference, Python frees it right away.
Streaming large inputs
The most common real use is reading data that is bigger than you want to hold in memory. File objects are already lazy iterators over lines.
import io
def count_errors(lines):
return sum(1 for line in lines if "ERROR" in line)
log = io.StringIO("INFO ok\nERROR disk\nINFO ok\nERROR net\n")
print(count_errors(log)) # 2With a real file you would write with open("app.log") as f: count_errors(f). The file could be 20 GB and the function would still use a few kilobytes, since only one line is held at a time. Calling f.readlines() or list(f) instead would try to load the whole file.
Getting the first answer sooner
Laziness also reduces time, not just memory, when you do not need every value. A consumer that stops early stops the producer too.
def numbers():
for n in range(1, 1_000_000_000):
print("producing", n)
yield n
first_big = next(n for n in numbers() if n > 3)
print("result:", first_big)The output is producing 1 through producing 4, then result: 4. The remaining values are never computed. The same behaviour applies to any(), all(), and next(..., default), which short-circuit on the first decisive value.
An eager version, [n for n in numbers()], would try to produce a billion values before you could look at the first.
Infinite and open-ended streams
Eager evaluation cannot represent an infinite sequence. A lazy one can, as long as the consumer takes a finite part. itertools.islice does the slicing without materialising anything.
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 8))) # [0, 1, 1, 2, 3, 5, 8, 13]The while True loop is safe because the generator is suspended at every yield. It only advances when islice asks for another value. Sensor feeds, network messages and event queues fit this model, since their length is unknown in advance.
Tradeoffs and gotchas
Laziness has costs. The table summarises the main decision points.
| Concern | Eager (list) | Lazy (generator) |
|---|---|---|
| Peak memory | Grows with the number of items | Roughly constant |
| Random access, `len()`, slicing | Supported | Not supported |
| Reuse for a second pass | Yes | No, it is exhausted after one pass |
| Errors in the data | Raised at creation | Raised later, during consumption |
| Debugging | Easy to print and inspect | Inspecting a value consumes it |
| Speed on small data | Often slightly faster | Per-item overhead of resuming the frame |
Errors appear late
A generator body does not run when you call the function. A bad input is therefore reported where the value is consumed, which may be far from where the generator was built.
def parse(values):
for v in values:
yield int(v)
parsed = parse(["1", "2", "x"])
print("created") # no error yet
try:
print(list(parsed))
except ValueError as exc:
print("error:", exc)The output is created, then error: invalid literal for int() with base 10: 'x'. If you want validation to fail at call time, check the arguments in a normal function that then returns the generator.
Variables are read when values are needed
The outermost iterable of a generator expression is evaluated immediately. Everything else is looked up on each step. If you change a variable between creation and consumption, the generator sees the new value.
n = 2
gen = (x * n for x in range(3))
n = 10
print(list(gen)) # [0, 10, 20]The same applies to a list you are iterating over. If you append to it before the generator reaches the end, the new items are included. When this matters, pass copies or finish consuming the generator before changing its inputs.
Laziness does not mean less total work
A lazy pipeline that reads every item does the same amount of computation as an eager one, plus the small cost of suspending and resuming. The gain comes from not holding data and from stopping early. Do not convert code to generators just to make it faster.
Some functions force full materialisation
list(), sorted(), set(), tuple(), statistics.median() and similar calls consume the whole iterable into memory. Placing one in the middle of a lazy pipeline removes the savings at that point. sorted is the usual surprise, because it cannot emit the first value until it has seen the last. Reductions such as sum, min, max and any do not have this problem.
Do not keep references
A generator only saves memory if you let go of what it yields. This code defeats the purpose:
results = []
for value in (x * x for x in range(1_000_000)):
results.append(value) # the full list is back in memoryIf you need the values later, a list is the honest choice. If you need only a summary, update the summary inside the loop and discard value.
A rule of thumb
Use a list when you need to index, measure, sort, or iterate more than once, and the data comfortably fits in memory. Use a generator when you will pass over the data once, the data is large or unbounded, or you may stop early. When you are unsure, write the lazy version first. Wrapping it in list() later is a one-word change, while turning an out-of-memory list into a stream usually means restructuring.
Exercise
You write total = sum([len(line) for line in big_file]) and the program runs out of memory on a 30 GB file. What is the one-line fix, and why does it work?
Show answer
Remove the square brackets: total = sum(len(line) for line in big_file). The list comprehension builds a list holding one integer per line before sum starts. The generator expression hands sum one length at a time, and each is discarded after being added, so memory use stays constant. The file object is already a lazy iterator over lines, so it never loads the whole file either.
Exercise
What does this code print, and why? gen = (n * 2 for n in range(3)) print(sum(gen)) print(sum(gen))
Show answer
It prints 6 and then 0. The first sum consumes the generator completely (0 + 2 + 4 = 6). A generator cannot be rewound, so the second sum receives an exhausted iterator with no values and returns the start value 0. To sum twice, build the generator again or store the values in a list.
Exercise
Why is sorted(x for x in stream) not a memory-saving use of a generator expression, even though the argument is lazy?
Show answer
sorted must see every value before it can return the first one, so it collects the whole input into a list internally. The generator expression saves nothing because the full data ends up in memory anyway. Memory savings only hold when each stage of the pipeline can pass values on one at a time, as sum, max, any and islice do.