Part 3. Lazy evaluation: generators and iterators#
In programming, the word “laziness” has a second, technical meaning. Lazy evaluation means
that a value is computed only when someone needs it, not in advance. In Python, range objects
and iterators are lazy: map, filter, zip, the functions of the itertools module, and above all
generators, that is, functions with a yield statement and generator expressions. Laziness brings
three benefits. A computation can finish earlier, there is no need to store all the values at
once, and one can work with infinite sequences. It also has two drawbacks: a generator yields each
value only once, and yielding values one at a time costs some time. The examples with the Collatz
sequence and the sieve of Eratosthenes draw on the chapter on functional programming in the book
by T. Altenkirch and I. Triguero, Conceptual Programming with Python (2020).
import itertools
import math
from itertools import count, islice
srodowisko("numpy", "sympy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, numpy 2.5.3, sympy 1.14.0
The Collatz sequence as a generator#
In Lecture 1, the function collatz built a list of all the terms of a trajectory. The version
with yield produces the terms one at a time. After each yield, the function is suspended and
resumes only when someone asks for the next value.
def collatz_lista(n):
ciag = [n]
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
ciag.append(n)
return ciag
def collatz(n):
"""Kolejne wyrazy trajektorii Collatza od n do 1, leniwie, po jednym."""
while n != 1:
yield n
n = n // 2 if n % 2 == 0 else 3 * n + 1
yield 1
print("pierwsze wyrazy:", list(islice(collatz(27), 12)))
print("liczba kroków:", sum(1 for _ in collatz(27)) - 1,
" największy wyraz:", max(collatz(27)))
pierwsze wyrazy: [27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107]
liczba kroków: 111 największy wyraz: 9232
Let us ask for the first term of the trajectory of \(27\) that is greater than \(1000\). The list has to be built in full before we can start searching it. The generator stops at the first matching term:
pozycja, wyraz = next((k, v) for k, v in enumerate(collatz(27)) if v > 1000)
print(f"pierwszy wyraz > 1000: {wyraz} (wyraz numer {pozycja})")
print(f"lista policzyła {len(collatz_lista(27))} wyrazów,",
f"generator {pozycja + 1}")
pierwszy wyraz > 1000: 1186 (wyraz numer 36)
lista policzyła 112 wyrazów, generator 37
The function next takes one value from the generator, and enumerate attaches an index to each
term. Both are lazy, so the whole pipeline computes exactly as many terms as the answer requires.
Short-circuit evaluation: any, all, next#
The functions all and any stop as soon as they know the answer: all at the first false
value, any at the first true one. With a generator, they also save computing the remaining
values. Not so with a list, because the list is complete before all receives its first element.
Let us check this on a primality test by trial division, for a large even number:
def pierwsza(n):
return n > 1 and all(n % d for d in range(2, math.isqrt(n) + 1))
def pierwsza_lista(n):
return n > 1 and all([n % d for d in range(2, math.isqrt(n) + 1)])
czasy_spiecie = porownaj({"all(lista)": pierwsza_lista,
"all(generator)": pierwsza}, 10**12 + 2)
wariant czas przyspieszenie
all(lista) 23.6 ms 1.0×
all(generator) 337 ns 69963×
The list version computes a million remainders, the generator version just one: the remainder of
division by \(2\) is \(0\), and all immediately returns False. The difference reaches several
orders of magnitude.
Short-circuit evaluation comes in handy when searching for counterexamples. Euler noticed that the polynomial \(n^2+n+41\) gives primes for many consecutive \(n\). Does it do so for all of them?
testy = 0
def euler_pierwsza(n):
global testy
testy += 1
return pierwsza(n * n + n + 41)
print("pierwsze dla n < 100:", all(euler_pierwsza(n) for n in range(100)),
f"(wykonano {testy} testów)")
n0 = next(n for n in count() if not pierwsza(n * n + n + 41))
print(f"pierwszy kontrprzykład: n = {n0}, n² + n + 41 = {n0*n0 + n0 + 41}",
f"= {math.isqrt(n0*n0 + n0 + 41)}²")
pierwsze dla n < 100: False (wykonano 41 testów)
pierwszy kontrprzykład: n = 40, n² + n + 41 = 1681 = 41²
The function all stopped at the first counterexample and performed only as many tests as were
needed. To find the counterexample, we used the infinite counter count(). This works because
next stops at the first matching \(n\). For \(n=40\) we have \(n^2+n+41=40\cdot41+41=41^2\), so the
counterexample is also easy to see without a computer.
Memory: a generator does not store values#
A list comprehension creates all the values at once and keeps them in memory. A generator keeps
only its current state in memory. Let us measure the peak memory usage while summing a million
squares, using the tracemalloc module, which tracks the memory allocations made by Python.
import tracemalloc
def szczyt_pamieci(f, *args):
"""Największa ilość pamięci przydzielonej podczas f(*args), w bajtach."""
tracemalloc.start()
f(*args)
szczyt = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
return szczyt
def kwadraty_lista(n):
return sum([k * k for k in range(n)])
def kwadraty_generator(n):
return sum(k * k for k in range(n))
def rozmiar(bajty):
for jednostka, skala in (("MiB", 2**20), ("KiB", 2**10)):
if bajty >= skala:
return f"{bajty / skala:.1f} {jednostka}"
return f"{bajty} B"
pamiec = {f.__name__: szczyt_pamieci(f, 10**6)
for f in (kwadraty_lista, kwadraty_generator)}
for nazwa, bajty in pamiec.items():
print(f"{nazwa:19} szczyt pamięci: {rozmiar(bajty)}")
czasy_pamiec = porownaj({"lista": kwadraty_lista,
"generator": kwadraty_generator}, 10**6)
kwadraty_lista szczyt pamięci: 38.6 MiB
kwadraty_generator szczyt pamięci: 464 B
wariant czas przyspieszenie
lista 23.9 ms 1.0×
generator 24.8 ms 0.97×
The list takes up tens of megabytes: a million pointers and a million integer objects. The generator needs less than a kilobyte, regardless of \(n\). The running times of the two versions are similar. The list sometimes wins slightly, because it does not have to suspend and resume a generator, but with large data this gain stops mattering once memory runs short.
range is lazy, too. The object range(10**12) takes up a few dozen bytes, and checking whether
a number belongs to it is a computation, not a scan:
import sys
r12 = range(10**12)
print("rozmiar obiektu range(10**12):", sys.getsizeof(r12), "bajtów")
print("10**12 - 1 in range(10**12):", 10**12 - 1 in r12,
" czas:", czas(zmierz(lambda: 10**12 - 1 in r12)))
rozmiar obiektu range(10**12): 48 bajtów
10**12 - 1 in range(10**12): True czas: 56.3 ns
Infinite sequences: prime numbers#
Altenkirch and Triguero show how to write the sieve of Eratosthenes lazily. We take the sequence
of natural numbers starting from \(2\). Its first term \(p\) is a prime, so we yield it, and we sieve
the rest of the sequence, removing the multiples of \(p\). The sequence of natural numbers is also
written recursively: the number \(n\), followed by the numbers from \(n+1\) on. The statement
yield from passes on all the values of another generator.
def naturalne(n):
yield n
yield from naturalne(n + 1)
def sito(liczby):
p = next(liczby)
yield p
yield from (k for k in sito(liczby) if k % p != 0)
print(list(islice(sito(naturalne(2)), 15)))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
The code is short and beautiful. But let us try to take more primes:
def ile_przed_bledem(generator):
ile = ostatnia = 0
try:
for ostatnia in generator:
ile += 1
except RecursionError:
return ile, ostatnia
for opis, liczby in (("naturalne(2)", naturalne(2)), ("count(2)", count(2))):
ile, ostatnia = ile_przed_bledem(sito(liczby))
print(f"sito({opis}): RecursionError po {ile} liczbach pierwszych",
f"(ostatnia {ostatnia})")
sito(naturalne(2)): RecursionError po 66 liczbach pierwszych (ostatnia 317)
sito(count(2)): RecursionError po 93 liczbach pierwszych (ostatnia 487)
The program fails with a RecursionError after only a few dozen primes. Every prime found adds a
new layer of generators: a number on its way to the output passes through the filters of all the
earlier primes, and each filter is another call on the stack. In Python, the stack has a limited
depth. The recursive sequence naturalne adds layers of its own, so with itertools.count we get
a little further, but not far.
There is also a second, less visible problem. M. E. O’Neill (The Genuine Sieve of Eratosthenes, J. Funct. Programming 2009) observed that this is not the sieve of Eratosthenes at all. Here, every prime \(q\) is divided by all the smaller primes. The sieve only crosses out multiples, and trial division checks divisors only up to \(\sqrt q\). Let us count the divisions made while finding the primes below \(300\):
dzielenia = 0
def niepodzielna(k, p):
global dzielenia
dzielenia += 1
return k % p != 0
def sito_liczace(liczby):
p = next(liczby)
yield p
yield from (k for k in sito_liczace(liczby) if niepodzielna(k, p))
def dzielenia_testu(N):
"""Dzielenia w teście d = 2, 3, ..., √k dla wszystkich k < N."""
ile = 0
for k in range(2, N):
for d in range(2, math.isqrt(k) + 1):
ile += 1
if k % d == 0:
break
return ile
pierwsze_300 = list(itertools.takewhile(lambda p: p < 300,
sito_liczace(count(2))))
dzielenia_sita, dzielenia_proby = dzielenia, dzielenia_testu(300)
print(f"liczb pierwszych < 300: {len(pierwsze_300)}")
print(f"leniwe „sito”: {dzielenia_sita} dzieleń;",
f"dzielenie przez d ≤ √k: {dzielenia_proby} dzieleń")
liczb pierwszych < 300: 62
leniwe „sito”: 31668 dzieleń; dzielenie przez d ≤ √k: 1066 dzieleń
The lazy “sieve” performed many times more divisions than ordinary trial division, which for each number \(k\) checks the divisors \(2,3,\dots\) until it finds the first divisor or reaches \(\sqrt k\).
A genuine lazy sieve keeps a dictionary: for each upcoming composite number, it remembers the primes that will cross it out. A number that is not in the dictionary is prime. We then record that \(p\) will first cross out \(p^2\). A number found in the dictionary is composite. We then move each of its primes on to the next multiple of that prime. The generator is infinite and uses no recursion.
def pierwsze():
"""Wszystkie liczby pierwsze po kolei: leniwe sito ze słownikiem."""
skresli = {} # liczba złożona → liczby pierwsze, które ją skreślą
for n in count(2):
if n not in skresli:
yield n
skresli[n * n] = [n]
else:
for p in skresli.pop(n):
skresli.setdefault(n + p, []).append(p)
print(list(islice(pierwsze(), 15)), "...",
next(islice(pierwsze(), 9999, None)))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] ... 104729
The last number is the ten-thousandth prime. When an upper bound is known, the fastest option is
the ordinary, “eager” sieve on a byte array. The slice assignment jest[p*p::p] crosses out all
the multiples of \(p\) in a single operation in C. Let us compare all the versions, first for the
numbers below \(300\), because the lazy “sieve” does not reach any further:
import numpy as np
from sympy import primepi
from sympy.ntheory.generate import Sieve
def lp_leniwe_sito(N):
return list(itertools.takewhile(lambda p: p < N, sito(count(2))))
def lp_dzielenie(N):
return [n for n in range(2, N) if pierwsza(n)]
def lp_slownik(N):
return list(itertools.takewhile(lambda p: p < N, pierwsze()))
def lp_tablica(N):
jest = bytearray([1]) * N
jest[0] = jest[1] = 0
for p in range(2, math.isqrt(N - 1) + 1):
if jest[p]:
jest[p * p::p] = bytes(len(range(p * p, N, p)))
return list(itertools.compress(range(N), jest))
def lp_numpy(N):
jest = np.ones(N, dtype=bool)
jest[:2] = False
for p in range(2, math.isqrt(N - 1) + 1):
if jest[p]:
jest[p * p::p] = False
return np.flatnonzero(jest).tolist()
def lp_sympy(N):
return list(Sieve().primerange(2, N)) # nowe sito, bez pamięci
czasy_300 = porownaj({"leniwe „sito” z książki": lp_leniwe_sito,
"dzielenie do √n": lp_dzielenie,
"słownik (leniwe)": lp_slownik,
"tablica bajtów": lp_tablica,
"NumPy": lp_numpy, "SymPy Sieve": lp_sympy}, 300)
wariant czas przyspieszenie
leniwe „sito” z książki 913 µs 1.0×
dzielenie do √n 95.0 µs 9.6×
słownik (leniwe) 28.0 µs 33×
tablica bajtów 3.06 µs 298×
NumPy 3.15 µs 290×
SymPy Sieve 8.49 µs 108×
czasy_mln = porownaj({"słownik (leniwe)": lp_slownik,
"tablica bajtów": lp_tablica,
"NumPy": lp_numpy, "SymPy Sieve": lp_sympy}, 10**6)
print("liczb pierwszych < 10^6:", len(lp_tablica(10**6)),
" sympy.primepi:", primepi(10**6))
wariant czas przyspieszenie
słownik (leniwe) 167 ms 1.0×
tablica bajtów 10.1 ms 17×
NumPy 2.28 ms 73×
SymPy Sieve 19.6 ms 8.5×
liczb pierwszych < 10^6: 78498 sympy.primepi: 78498
There are three conclusions. The elegant lazy “sieve” is the slowest, slower even than plain trial
division, and it does not get far. The genuine lazy sieve with a dictionary is many times slower
than the byte array, but it does not need to know an upper bound. That is the price of laziness,
sometimes worth paying. The fastest is the NumPy version, which crosses out with slices in the
same way, only without converting the array into a list of Python numbers along the way (more on
NumPy in part 5). A symbolic library need not be the fastest: here SymPy’s sieve
loses to a few lines of code on a byte array. The global sieve sympy.sieve, on the other hand,
remembers the numbers it has already sieved, so later queries about the same range are much
faster. In the measurement, we create a new sieve (Sieve()) so as not to measure this.
Iterators are one-shot#
Laziness has its pitfall, already familiar from part 1. An exhausted iterator yields nothing and raises no error. A common mistake looks like this:
wartosci = map(lambda k: k * k, range(1, 6))
print("największa:", max(wartosci))
print("suma:", sum(wartosci)) # iterator jest już pusty!
największa: 25
suma: 0
The function max went through the whole iterator, so sum received an empty sequence and
returned \(0\). If the values are needed more than once, we store them in a list (list(map(...)))
or build the iterator anew. range objects and lists can be traversed many times. Generators,
map, filter, zip, and the objects from itertools are one-shot.
Lazy pipelines#
Iterators can be chained into pipelines. Each stage takes from the previous one as many values as it needs. Here are two examples. The first finds the first ten primes of the form \(n^2+1\), the second the smallest \(n\) for which the harmonic sum \(H_n=1+\tfrac12+\dots+\tfrac1n\) exceeds \(10\):
from itertools import accumulate
print(list(islice((n * n + 1 for n in count(1) if pierwsza(n * n + 1)), 10)))
sumy_czesciowe = accumulate(1 / k for k in count(1)) # H_1, H_2, ...
n10 = next(n for n, h in enumerate(sumy_czesciowe, start=1) if h > 10)
print("najmniejsze n z H_n > 10:", n10)
[2, 5, 17, 37, 101, 197, 257, 401, 577, 677]
najmniejsze n z H_n > 10: 12367
The function accumulate yields the partial sums, and enumerate(..., start=1) numbers them. No
stage knows how many values will be needed. The pipeline is stopped by islice or next. We
computed the result for \(H_n\) with float numbers, but \(H_{n-1}\) and \(H_n\) lie on either side of
\(10\) at a distance of order \(10^{-5}\), which is many times larger than the rounding errors, so the
result is certain. Let us check this exactly:
from fractions import Fraction
H = sum(Fraction(1, k) for k in range(1, n10))
print("H_(n-1) < 10 < H_n:", H < 10 < H + Fraction(1, n10))
print(f"10 - H_(n-1) ≈ {float(10 - H):.2e},",
f" H_n - 10 ≈ {float(H + Fraction(1, n10) - 10):.2e}")
H_(n-1) < 10 < H_n: True
10 - H_(n-1) ≈ 3.79e-05, H_n - 10 ≈ 4.30e-05
Summary#
Generators and iterators compute values on demand.
any,all,next, andislicestop as soon as they know the answer, so with a generator they do not compute unnecessary values.A generator does not store values: its memory usage does not depend on the length of the sequence.
rangeis lazy, too.Laziness makes it possible to work with infinite sequences (
count, generators withwhile True), but deep recursion of generators ends in aRecursionError, and elegant code does not guarantee a good algorithm.Iterators are one-shot. Values needed more than once are stored in a list.
When an upper bound is known, an eager array (a sieve on a
bytearray, NumPy) can be much faster than a lazy generator.
Exercises#
★ Write a generator
fibonacci()that yields all the Fibonacci numbers. Use it to find the first Fibonacci number with \(1000\) digits. What is its position in the sequence?★ Show that for every \(n\) the number \(n^2+n+41\) is not divisible by \(2,3,5,\dots,37\). Hint: check the residues modulo each of these primes for \(n=0,1,\dots,p-1\).
★★ Rewrite
sitoso that it takes a list of the primes found so far and checks only the divisors \(p\le\sqrt k\). Measure whether this helps, and explain whether it is now the sieve of Eratosthenes.★★ Measure the peak memory of
sorted(k * k % 1000 for k in range(10**6)). Doessortedwith a generator save memory? Why?