Sub topic 2
Why lazy iteration saves memory
This chapter assumes you can write functions, loops and comprehensions in Python and know how lists, tuples and strings behave. It also assumes you know the difference between an iterable and an iterator from the previous chapter. Generators and yield are helpful background but not required.
Eager and lazy evaluation
Eager evaluation computes every result up front and stores it. A list comprehension is eager. When [n * n for n in range(1_000_000)] finishes, a million integers exist in memory at once.
Lazy evaluation computes a result only when a consumer asks for it, then usually forgets it. A generator expression is lazy. (n * n for n in range(1_000_000)) builds a small object that remembers where it is and how to produce the next value. It produces no squares yet.
Every tool in itertools returns a lazy iterator. If you understand the memory model in this chapter, you will know when the module helps and when it makes no difference.
Measuring the difference
sys.getsizeof reports the size of an object itself. Compare a list with a generator that yields the same values:
import sys
squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))
print(sys.getsizeof(squares_list))
print(sys.getsizeof(squares_gen))On a typical 64-bit CPython build, the list reports about 8 MB and the generator reports a couple of hundred bytes. The list figure is only the array of pointers. Each integer object (about 28 bytes) lives elsewhere and is not counted, so the real cost of the list is several times larger.
The generator stays the same size whether it will produce one item or a billion. It stores only its paused frame: the loop position and the local variables.
To measure real peak usage, use tracemalloc, which tracks memory allocated by Python code:
import tracemalloc
def peak_kib(func):
tracemalloc.start()
func()
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak // 1024
def eager():
return sum([n * n for n in range(1_000_000)])
def lazy():
return sum(n * n for n in range(1_000_000))
print("eager peak KiB:", peak_kib(eager))
print("lazy peak KiB:", peak_kib(lazy))Both functions return the same number. The eager version peaks at tens of megabytes. The lazy version peaks at a few KiB or less, because sum takes one value, adds it to the total, and lets it go before asking for the next. Exact figures vary by Python version and platform, but the gap is large and the lazy figure does not grow with the input size.
How values are pulled
A lazy pipeline is pull-based. The final consumer asks for one item. That request travels backwards through each stage to the source, and one value travels forward. Nothing runs ahead of demand.
You can see this order by making a source that announces each item it produces:
from itertools import islice
def noisy(n):
for i in range(n):
print("producing", i)
yield i
doubled = (x * 2 for x in noisy(1_000_000))
print(list(islice(doubled, 2)))The output is:
producing 0
producing 1
[0, 2]The source holds a million potential items, but only two were ever created. The islice call stops after its second item without asking for a third. In an eager version, all million items would be produced first.
Early exit is the second saving
Laziness saves time as well as memory when you do not need every result. Searching a stream for the first match stops at that match:
from itertools import count
def first_square_over(limit):
squares = (n * n for n in count(1))
return next(s for s in squares if s > limit)
print(first_square_over(1000))This prints 1024. The source count(1) is infinite, yet the program finishes, because the consumer stops asking after 32 squares. An eager approach cannot even be written here, since a list of all squares never finishes building.
Constant memory over unbounded input
Data that does not fit in memory is the strongest case for laziness. A file object is itself a lazy iterator over lines, so this pattern works on a file of any size:
import io
def count_errors(lines):
return sum(1 for line in lines if line.startswith("error"))
log = io.StringIO("ok\nerror: disk\nok\nerror: net\nok\n")
print(count_errors(log))This prints 2. With a real file you would write with open("app.log") as f: count_errors(f). Only one line is held at a time, so a 50 GB log needs about as much memory as a 5 KB one. Calling f.readlines() instead would try to load the whole file.
The same applies to streams with no end, such as sensor readings, network messages and the output of count(). They can only be handled lazily.
Eager and lazy compared
| Property | Eager (list) | Lazy (iterator) |
|---|---|---|
| Memory use | Proportional to the number of items | Constant, roughly one item at a time |
| Work done up front | All of it | None until requested |
| Passes allowed | Any number | One |
| `len()`, indexing, slicing | Supported | Not supported (use `islice` for slicing) |
| Errors in the data | Raised when the list is built | Raised when the bad item is reached |
| Total CPU for a full pass | Similar | Similar, sometimes slightly higher per item |
Laziness does not make the total work smaller when you consume every item. It changes when the work happens and how much you hold at once.
Gotchas that come with laziness
One pass only
An iterator is exhausted after one full pass. A second pass over the same iterator yields nothing, and Python does not raise an error:
it = map(str, range(3))
print(list(it))
print(list(it))The output is ['0', '1', '2'] and then []. If you need several passes, either rebuild the pipeline each time or store the results in a list once.
Late binding of variables
A generator expression evaluates its outermost iterable immediately but evaluates everything else when each item is requested. Changing a variable between creating the generator and consuming it changes the result:
data = [1, 2, 3]
factor = 2
gen = (x * factor for x in data)
data = [10, 20]
factor = 10
print(list(gen))This prints [10, 20, 30]. The generator still uses the original data list, because that was captured at creation. It reads factor at consumption time, so the new value 10 applies. Avoid changing variables that a pending generator uses.
Deferred errors
If the third item of a lazy pipeline raises an exception, nothing happens until the consumer reaches it. A bug can look fine in a quick test that only looks at the first few items. Test the whole stream at least once.
Holding references defeats the saving
Laziness saves memory only if nothing keeps the items alive. Calling list(gen), storing every item in a dictionary, or keeping a reference to a long-lived list of results reintroduces the memory cost. Later chapters show the same trap with tee and groupby, which buffer items internally.
When eager is the better choice
Prefer a list when the data is small, when you need to loop over it more than once, or when you need len(), indexing or sorting. Sorting requires all the data anyway, so sorted() consumes the whole iterator and returns a list. For a few hundred items the memory saving is negligible, and a list is simpler to debug and print.
Exercise
A function returns (line.upper() for line in open_file). Another function returns [line.upper() for line in open_file]. The file has 10 million lines. Which function uses less memory, and what must the caller of the first one remember about the result?
Show answer
The first function, because it returns a generator that holds one line at a time, while the second builds a list of all 10 million upper-cased lines. The caller must remember that the generator can be consumed only once and that the file must stay open until the generator is exhausted. A second loop over it will yield nothing.
Exercise
What does this print, and why? from itertools import count gen = (n * n for n in count(1)) print(next(gen)) print(next(gen))
Show answer
It prints 1 and then 4. The generator is lazy, so each next() call computes exactly one more square from the infinite count(1) source. No other squares are created, and the program finishes without needing any memory beyond the current value.