Part 4. The standard library: built-in functions and data structures#
The simplest kind of laziness is not writing what has already been written. The built-in
functions (sum, min, max, sorted, any, all) and the modules of the standard library
(math, itertools, collections, heapq, bisect, functools) are written in C, tested, and
handle edge cases that are easy to forget. Then there is the choice of data structure: the same
operation on a list and on a set can differ in running time by three orders of magnitude. In this
part we will see examples from Lectures 1, 2, and 8. We will also check two popular beliefs that
measurement confirms only in part.
import bisect
import heapq
import itertools
import math
import random
from collections import Counter, defaultdict
from fractions import Fraction
srodowisko()
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11
Summation: a loop, sum, math.fsum#
In Lecture 1 (§1.4) we saw that, since
version 3.12, the function sum adds float numbers using compensated summation, and math.fsum
gives the correctly rounded sum. Let us add up a million copies of the number 0.1 and compare the
result with the exact sum in rational numbers. The value Fraction(0.1) is the exact value of the
machine number 0.1, which is slightly larger than \(1/10\).
dane = [0.1] * 10**6
dokladnie = Fraction(0.1) * 10**6 # dokładna suma liczb maszynowych
ulp = math.ulp(1e5) # odstęp liczb float w pobliżu 10^5
def suma_petla(xs):
s = 0.0
for v in xs:
s += v
return s
SUMY = {"pętla": suma_petla, "sum": sum, "math.fsum": math.fsum}
for nazwa, f in SUMY.items():
w = f(dane)
blad = abs(Fraction(w) - dokladnie) / Fraction(ulp)
print(f"{nazwa:10} {w!r:22} błąd: {float(blad):9.1f} ulp")
print("dokładna suma zaokrąglona do float:", float(dokladnie))
czasy_suma = porownaj(SUMY, dane, zgodne=lambda a, b: True)
pętla 100000.00000133288 błąd: 91594.6 ulp
sum 100000.0 błąd: 0.4 ulp
math.fsum 100000.0 błąd: 0.4 ulp
dokładna suma zaokrąglona do float: 100000.0
wariant czas przyspieszenie
pętla 8.17 ms 1.0×
sum 3.58 ms 2.3×
math.fsum 3.59 ms 2.3×
The loop adds from left to right and is off by tens of thousands of ulps, that is, in the sixth
digit after the decimal point. The functions sum and math.fsum return the correctly rounded sum
here, and they are faster than the loop as well. So the lazy choice is both faster and more
accurate. For float data, math.fsum is a good default: it guarantees correct rounding, while
sum only reduces the error. In the comparison, we allowed the results to differ
(zgodne=lambda a, b: True), because the difference in the results was exactly what we wanted to
show.
in: a list, a set, and binary search#
In Lecture 8 (§8.3) we check how many goals from the test set occur in the training data. For
this, the code builds the set stany = {p.stan for p in uczace} and asks p.stan in stany. Why a
set and not a list? The in operator on a list scans the elements one by one, so it costs \(O(n)\).
Sets and dictionaries are hash tables: they compute an element’s position in the table from its
value, so a membership test takes constant time on average. In between lies binary search in a
sorted list (the bisect module). It is the same bisection as in Lecture 5, only on integers, and
the same strategy as in the number-guessing game from Altenkirch and Triguero’s book: guess the
middle of the interval.
los = random.Random(2026)
elementy = [los.randrange(10**9) for _ in range(10**4)]
pytania = [los.randrange(10**9) for _ in range(1000)] + elementy[:1000]
zbior, posortowane = set(elementy), sorted(elementy)
def w_liscie(q):
return q in elementy
def w_zbiorze(q):
return q in zbior
def binarnie(q):
i = bisect.bisect_left(posortowane, q)
return i < len(posortowane) and posortowane[i] == q
czasy_in = porownaj({
"lista: in": lambda: sum(map(w_liscie, pytania)),
"posortowana lista: bisect": lambda: sum(map(binarnie, pytania)),
"zbiór: in": lambda: sum(map(w_zbiorze, pytania))})
t_zbior = zmierz(set, elementy)
t_pytanie = czasy_in["lista: in"] / len(pytania) # jedno pytanie do listy
print("budowa zbioru:", czas(t_zbior),
"| sortowanie listy:", czas(zmierz(sorted, elementy)))
print(f"budowa zbioru trwa tyle, co {t_zbior / t_pytanie:.0f} pytań do listy")
wariant czas przyspieszenie
lista: in 37.6 ms 1.0×
posortowana lista: bisect 301 µs 125×
zbiór: in 51.5 µs 731×
budowa zbioru: 107 µs | sortowanie listy: 500 µs
budowa zbioru trwa tyle, co 6 pytań do listy
For ten thousand elements, the set answers two thousand queries more than a hundred times faster
than the list, and binary search lies in between. Building the set is a one-time cost, roughly
that of a few to a dozen or so queries to the list (the last line of the output), so it pays off
quickly. A sorted list with bisect is useful when, besides the question “is it there?”, we also
ask questions about order, for example, “how many elements are smaller than \(q\)?” A set cannot
answer such questions.
Counting occurrences: Counter#
The frequency model from Lecture 8 counts how often each tactic appears in the data. The tool for
counting occurrences is collections.Counter. Let us take an example from number theory. The last
digits of primes greater than \(5\) are \(1\), \(3\), \(7\), or \(9\). Do they occur equally often? And what
do the last digits of consecutive primes look like?
def pierwsze_ponizej(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))
P = pierwsze_ponizej(10**6)
cyfry = [p % 10 for p in P]
print("ostatnie cyfry:", " ".join(f"{c}: {ile}" for c, ile
in sorted(Counter(cyfry).items())))
pary = Counter(zip(cyfry, cyfry[1:]))
for a in (1, 3, 7, 9):
print(f"po liczbie pierwszej z końcówką {a}:",
" ".join(f"{b}: {pary[a, b]:5}" for b in (1, 3, 7, 9)))
ostatnie cyfry: 1: 19617 2: 1 3: 19665 5: 1 7: 19621 9: 19593
po liczbie pierwszej z końcówką 1: 1: 3213 3: 6299 7: 6550 9: 3555
po liczbie pierwszej z końcówką 3: 1: 4387 3: 2810 7: 5819 9: 6647
po liczbie pierwszej z końcówką 7: 1: 5069 3: 5443 7: 2873 9: 6236
po liczbie pierwszej z końcówką 9: 1: 6948 3: 5112 7: 4378 9: 3155
The individual digits are distributed almost evenly. Pairs of consecutive primes are not: after a prime ending in the digit \(a\), the next prime ends in the same digit noticeably less often. This phenomenon was described by R. J. Lemke Oliver and K. Soundararajan (Unexpected biases in the distribution of consecutive primes, PNAS 2016). Now let us measure how much the counting itself costs:
def licz_slownik(xs):
d = {}
for x in xs:
if x in d:
d[x] += 1
else:
d[x] = 1
return d
def licz_defaultdict(xs):
d = defaultdict(int)
for x in xs:
d[x] += 1
return dict(d)
pary_cyfr = list(zip(cyfry, cyfry[1:]))
czasy_licz = porownaj({"słownik i if": licz_slownik,
"defaultdict": licz_defaultdict,
"Counter": lambda xs: dict(Counter(xs))}, pary_cyfr)
wariant czas przyspieszenie
słownik i if 4.37 ms 1.0×
defaultdict 3.50 ms 1.2×
Counter 2.40 ms 1.8×
Counter is faster than a hand-written loop, and it is also shorter and has ready-made methods,
for example most_common. The difference is not large here, because every version has to go
through all the data. Here laziness pays off mainly in readability.
The \(k\) smallest elements: heapq#
The \(k\)-nearest-neighbors method (kNN) from Lecture 8 looks for the \(k\) most similar examples
among all the training data. Sorting all the distances costs \(O(n\log n)\), but we only need the
\(k\) smallest. A heap from the heapq module finds them in time \(O(n\log k)\).
odleglosci = [los.random() for _ in range(10**5)]
czasy_k = porownaj({
"sorted(...)[:5]": lambda: sorted(odleglosci)[:5],
"heapq.nsmallest(5, ...)": lambda: heapq.nsmallest(5, odleglosci),
"min (gdy k = 1)": lambda: [min(odleglosci)]},
zgodne=lambda a, b: a[0] == b[0])
wariant czas przyspieszenie
sorted(...)[:5] 8.59 ms 1.0×
heapq.nsmallest(5, ...) 523 µs 16×
min (gdy k = 1) 377 µs 23×
The heap is many times faster than sorting the whole list. When only a single nearest neighbor is
needed, a plain min is enough.
Building lists: append or l = l + [x]#
The first version of the function collatz in Altenkirch and Triguero’s book adds successive
terms with the statement l = l + [n]. This looks innocent, but l + [n] creates a new list
and copies all the existing elements into it. Building a list of length \(n\) therefore costs
\(1+2+\dots+n\approx n^2/2\) copy operations. The method append adds the element in place, in
constant time on average. A list reserves spare memory and enlarges it from time to time, in
proportion to its length. Let us measure the running times for growing \(n\):
def doklejanie(n):
l = []
for k in range(n):
l = l + [k]
return l
def dopisywanie(n):
l = []
for k in range(n):
l.append(k)
return l
def skladana(n):
return [k for k in range(n)]
rozmiary = [2500, 5000, 10000, 20000]
serie = {"l = l + [x]": [zmierz(doklejanie, n) for n in rozmiary],
"l.append(x)": [zmierz(dopisywanie, n) for n in rozmiary],
"lista składana": [zmierz(skladana, n) for n in rozmiary]}
assert doklejanie(1000) == dopisywanie(1000) == skladana(1000)
print(f"{'n':15}", " ".join(f"{n:>8}" for n in rozmiary),
" czas(2n)/czas(n)")
for nazwa, t in serie.items():
print(f"{nazwa:15}", " ".join(czas(v).rjust(8) for v in t),
f" {(t[-1] / t[0]) ** (1 / 3):10.1f}")
wykres_skalowania(rozmiary, serie, "Budowanie listy długości n")
n 2500 5000 10000 20000 czas(2n)/czas(n)
l = l + [x] 2.90 ms 14.8 ms 73.5 ms 329 ms 4.8
l.append(x) 28.5 µs 55.5 µs 112 µs 222 µs 2.0
lista składana 22.7 µs 46.5 µs 94.0 µs 175 µs 2.0
When \(n\) doubles, the running time of l = l + [x] roughly quadruples, while that of append
doubles. On the log-log plot, this shows up as slopes \(2\) and \(1\). The list comprehension is even
faster than append, because it does not call a method at every step. A quadratic cost hidden in
innocent-looking code is the most common reason why programs run fine on small data and “hang” on
large data.
Strings: join and +=#
For the same reason, textbooks recommend concatenating strings with "".join(...) rather than
with += in a loop. Strings in Python are immutable, so s += t ought to create a new string. Let
us check how the running time grows when we add to the end, when we add to the beginning, and when
we use join:
kawalki = [str(k) for k in range(4 * 10**5)]
def na_koncu(xs):
s = ""
for x in xs:
s += x
return s
def na_poczatku(xs):
s = ""
for x in reversed(xs):
s = x + s
return s
czasy_napisy = porownaj({"s += x (na końcu)": na_koncu,
"s = x + s (na początku)": na_poczatku,
"join": "".join}, kawalki[:20000])
for f in (na_koncu, na_poczatku):
t1, t4 = zmierz(f, kawalki[:20000]), zmierz(f, kawalki[:80000])
print(f"{f.__name__}: czterokrotnie dłuższe dane, czas × {t4 / t1:.1f}")
wariant czas przyspieszenie
s += x (na końcu) 480 µs 1.0×
s = x + s (na początku) 18.9 ms 0.03×
join 59.6 µs 8.0×
na_koncu: czterokrotnie dłuższe dane, czas × 3.9
na_poczatku: czterokrotnie dłuższe dane, czas × 12.7
The result is more interesting than the textbook rule. Adding to the end scales linearly: CPython
extends the string in place when nothing else holds a reference to it. This, however, is an
implementation detail, not a guarantee of the language. The PEP 8 style guide explicitly advises
against relying on it, because Python implementations without reference counting do not have it.
Adding to the beginning scales quadratically, because each step copies the whole string. The
function join is the fastest in all cases, because it first computes the length of the result
and then copies each piece once. The conclusion: join is the safe choice, and measurement shows
when the difference really matters.
Combinatorics: itertools and math#
The itertools module provides ready-made combinatorial iterators: product, permutations,
combinations. In Lecture 6 (§6.3), this is how product enumerates the exponents of the
monomials up to a given degree. Is a ready-made iterator faster than a loop? Let us compare three
tasks: listing all the permutations of \(8\) elements (our own recursion in the spirit of the chapter
on combinatorics in Altenkirch and Triguero’s book, against itertools.permutations), listing the
pairs \(i<j\), and counting the triples \(i<j<k\).
def permutacje(xs):
if len(xs) <= 1:
yield tuple(xs)
return
for i, x in enumerate(xs):
for reszta in permutacje(xs[:i] + xs[i + 1:]):
yield (x,) + reszta
def pary_petle(n):
return [(i, j) for i in range(n) for j in range(i + 1, n)]
def trojki_petle(n):
return sum(1 for i in range(n) for j in range(i + 1, n)
for k in range(j + 1, n))
def trojki_combinations(n):
return sum(1 for _ in itertools.combinations(range(n), 3))
czasy_perm = porownaj({
"własna rekurencja": lambda: list(permutacje(list(range(8)))),
"itertools.permutations": lambda: list(itertools.permutations(range(8)))})
czasy_pary = porownaj({
"dwie pętle": lambda: pary_petle(1000),
"itertools.combinations":
lambda: list(itertools.combinations(range(1000), 2))})
czasy_trojki = porownaj({"trzy pętle": trojki_petle,
"combinations": trojki_combinations,
"math.comb(100, 3)": lambda n: math.comb(n, 3)}, 100)
wariant czas przyspieszenie
własna rekurencja 17.8 ms 1.0×
itertools.permutations 1.05 ms 17×
wariant czas przyspieszenie
dwie pętle 15.6 ms 1.0×
itertools.combinations 11.3 ms 1.4×
wariant czas przyspieszenie
trzy pętle 2.20 ms 1.0×
combinations 3.36 ms 0.66×
math.comb(100, 3) 43.8 ns 50236×
For permutations, the ready-made iterator wins many times over, because our own recursion creates
a multitude of intermediate lists and tuples. For pairs, the difference is small, and for counting
triples the iterator does not win clearly, because combinations creates a tuple for each triple,
which we do not use anyway. The gain from itertools is above all readability and laziness.
Speed comes only when the iterator replaces a lot of work done in Python. Orders of magnitude come
only from mathematics: the number of triples is given by the formula \(\binom{100}{3}\).
math and pow: exact functions on integers#
The math module has functions that compute exactly with integers of any size: isqrt, gcd,
lcm, comb, perm, factorial, prod. Replacing them with computations on float numbers can
be not only slower but also wrong. The integer part of a square root computed via float is wrong
when the number has more than \(15\)–\(16\) digits:
n = 10**16 - 1
print("int(math.sqrt(n)) =", int(math.sqrt(n)),
" math.isqrt(n) =", math.isqrt(n))
print("sprawdzenie isqrt:", math.isqrt(n)**2 <= n < (math.isqrt(n) + 1)**2)
int(math.sqrt(n)) = 100000000 math.isqrt(n) = 99999999
sprawdzenie isqrt: True
The number \(10^{16}-1\) is not a machine number, so float(n) rounds it to \(10^{16}\), whose square
root is exactly \(10^8\). Yet \((10^8)^2>n\), so the correct answer is \(10^8-1\).
With a third argument, the built-in function pow computes a power modulo \(m\) by fast
exponentiation. It performs about \(\log_2 b\) multiplications of numbers smaller than \(m\). The
expression a**b % m first computes the whole power, which for \(b=10^6\) has hundreds of thousands
of digits, and only then divides:
m = 1_000_003
print("3**(10**6) ma", math.floor(10**6 * math.log10(3)) + 1, "cyfr")
czasy_pow = porownaj({"3**(10**6) % m": lambda: 3**(10**6) % m,
"pow(3, 10**6, m)": lambda: pow(3, 10**6, m)})
print("odwrotność 3 modulo m: pow(3, -1, m) =", pow(3, -1, m),
" sprawdzenie:", 3 * pow(3, -1, m) % m)
3**(10**6) ma 477122 cyfr
wariant czas przyspieszenie
3**(10**6) % m 43.7 ms 1.0×
pow(3, 10**6, m) 447 ns 97716×
odwrotność 3 modulo m: pow(3, -1, m) = 666669 sprawdzenie: 1
The three-argument pow is more than ten thousand times faster. The Fermat primality test and RSA
cryptography rest on it. Since Python 3.8, pow(a, -1, m) also computes the inverse modulo \(m\).
We computed the number of digits of the power with the formula \(\lfloor b\log_{10}3\rfloor+1\), not
with len(str(...)). Since version 3.11, Python refuses to convert an integer with more than
\(4300\) digits to a string and raises ValueError. This protects servers against attacks in which
someone submits a gigantic number for conversion. Python stores integers in binary, and the
conversion to decimal notation and back cannot be done in linear time, so for very long numbers it
takes a long time. The limit can be changed with the function sys.set_int_max_str_digits.
Summary#
Before you write a loop, check the built-in functions and the standard library:
sum,math.fsum,Counter,heapq,bisect,itertools,math,pow. They are usually faster, and often more accurate, too (fsum,isqrt).The data structure determines the complexity:
inon a list is \(O(n)\), on a set or in a dictionary \(O(1)\) on average, and in a sorted list withbisect\(O(\log n)\).Watch out for a quadratic cost hidden in innocent-looking code:
l = l + [x]in a loop, adding to the beginning of a string. Useappend, list comprehensions, andjoin.Popular rules are worth checking by measurement:
+=at the end of a string is not quadratic in CPython, anditertoolsis not always faster than a loop.
Exercises#
★ Write a function that computes the \(\gcd\) of many numbers in a loop, calling
math.gcdwith two arguments, and compare it withmath.gcd(*liczby)for \(10^5\) random numbers.★ Count the pairs of last digits of consecutive primes below \(10^7\). Does the unevenness grow or shrink?
★★ Implement the Fermat primality test: \(n\) is “probably prime” if \(a^{n-1}\equiv1\pmod n\) for several random \(a\). Compare the running times of
pow(a, n - 1, n)anda**(n - 1) % nfor \(n\) with \(50\) digits. Find the smallest Carmichael number that fools this test.★★ For a list of length \(n\), compare
x in listawithx in set(lista), including the construction of the set every time. After how many queries does building the set pay off?