Skip to content

09. Standard library power tools

Python ships with hundreds of modules. A small set of them solves most everyday data problems: counting, grouping, rolling windows, dates, log parsing, quick statistics, random samples and file automation. This module tours that set. Every tool is shown on the course datasets: sales lines, sensor readings, the application log and the A/B test.

  • Count, group, window and label records with Counter, defaultdict, deque and namedtuple.
  • Chain, slice, batch, group, pair and combine streams of records with itertools.
  • Fix arguments with partial, fold a sequence with reduce and skip repeated work with lru_cache and cache.
  • Parse, compute and format dates and times, and convert them between time zones with daylight saving time.
  • Extract fields from log lines with regular expressions: groups, named groups, findall, sub, compiled patterns and flags.
  • Do quick numeric work with math, statistics and a seeded random.Random, and automate files and programs with os, sys, shutil and subprocess.

Module 08 introduced the standard library: the set of modules that comes with every Python installation. You import its modules; you never install them. They are tested, documented and stable across versions. Python’s motto for this is “batteries included”.

Learn the standard library before you reach for a package. A script that uses only the standard library runs on any machine with Python. It needs no environment and no requirements.txt. pandas and NumPy (Part 4) are faster on big tables, but they are built on the same ideas: counting, grouping, windows, dates and patterns.

Module Job Data example in this module
collections specialized containers units sold per product, orders per region, a rolling window
itertools fast tools for loops over sequences monthly running totals, a grid of model settings
functools tools for functions a cached lookup, a function with fixed settings
operator operators as functions sort and group records by a field
datetime, zoneinfo dates, times, durations, time zones pipeline run times in UTC and local time
re regular expressions parse data/logs/app.log
math, statistics, random numbers, summary statistics, random samples a bootstrap confidence interval
os, sys, shutil the operating system, the interpreter, file copies back up the monthly reports
subprocess run other programs run a check script in a new process

Counting is the first question about almost any dataset: how many lines per category, how many units per product, how many requests per status code. A Counter from the collections module is a dict that maps each item to its count.

from collections import Counter
categories = ["Electronics", "Home", "Electronics", "Books", "Home", "Electronics"]
counts = Counter(categories)
print(counts)
print(counts["Electronics"], counts["Sports"])
print(counts.most_common(2))
Output
Counter({'Electronics': 3, 'Home': 2, 'Books': 1})
3 0
[('Electronics', 3), ('Home', 2)]

Counter(iterable) counts each item of the iterable. most_common(n) returns the n largest counts as (item, count) tuples, largest first. A missing key gives 0, not a KeyError, so counts["Sports"] is safe.

Counter is a subclass of dict (module 06), so it has every dict method, plus a few of its own. You can add counts one by one, with a weight, and combine counters with + and -:

week_1 = Counter({"P001": 12, "P014": 7, "P010": 5})
week_2 = Counter({"P001": 9, "P010": 8, "P025": 3})
print(week_1 + week_2)
print(week_1 - week_2)
both = week_1 + week_2
both["P014"] += 4 # four more units of P014
print(both.total())
Output
Counter({'P001': 21, 'P010': 13, 'P014': 7, 'P025': 3})
Counter({'P014': 7, 'P001': 3})
48

+ adds the counts of the same key. - subtracts and then drops every count that is zero or negative, so P010 (5 − 8) and P025 disappear. total() adds all counts. Use Counter whenever you write counts[key] = counts.get(key, 0) + 1.

To group records means to collect them under a key: all order lines of the North region, all readings of sensor S3. With a plain dict, you must check that the key exists before you append. A defaultdict creates the missing value for you.

from collections import defaultdict
lines = [("West", 66.49), ("West", 14.99), ("South", 19.99), ("West", 59.99)]
by_region = defaultdict(list)
for region, revenue in lines:
by_region[region].append(revenue)
print(dict(by_region))
Output
{'West': [66.49, 14.99, 59.99], 'South': [19.99]}

The argument of defaultdict is the default factory: a function that Python calls with no arguments when a key is missing. list() returns [], float() returns 0.0, int() returns 0 and set() returns an empty set. So defaultdict(float) sums revenue and defaultdict(set) collects unique order ids.

The factory runs on every read of a missing key, not only on writes:

print(len(by_region["East"]), "East" in by_region)
print(by_region.get("North"), "North" in by_region)
Output
0 True
None False

Reading by_region["East"] created an empty list for East. get() does not call the factory, so it is the safe way to look up a key that may be missing.

A deque (double-ended queue, said “deck”) is a sequence that adds and removes items at both ends in constant time. A queue is a line of items that you process in order, first in, first out. With a list, pop(0) takes linear time, because every other item moves one place to the left. With a deque, popleft() is constant time.

The maxlen argument makes a bounded deque. When it is full, each new item pushes out the oldest one at the other end. That is exactly a rolling window: the last n values of a stream, such as the last hour of sensor readings.

from collections import deque
window = deque(maxlen=3)
for reading in [21.0, 21.9, 21.4, 21.7, 22.1]:
window.append(reading)
print(list(window), round(sum(window) / len(window), 2))
Output
[21.0] 21.0
[21.0, 21.9] 21.45
[21.0, 21.9, 21.4] 21.43
[21.9, 21.4, 21.7] 21.67
[21.4, 21.7, 22.1] 21.73

The first two lines average fewer than 3 values, because the window is not full yet. From the fourth reading on, the oldest value falls out. A deque also works as a task queue:

tasks = deque(["load", "clean", "train"])
tasks.appendleft("validate") # urgent: goes to the front
first = tasks.popleft()
tasks.append("export")
print(first, list(tasks))
Output
validate ['load', 'clean', 'train', 'export']

A tuple is a good record, but row[3] does not say what the field means. namedtuple builds a new tuple type whose fields also have names.

from collections import namedtuple
Store = namedtuple("Store", ["store_id", "city", "region", "size_sqm"])
s01 = Store("S01", "Chicago", "North", 2850)
print(s01)
print(s01.city, s01[3])
store_id, city, region, size_sqm = s01
print(s01._replace(size_sqm=2900))
print(s01._asdict())
Output
Store(store_id='S01', city='Chicago', region='North', size_sqm=2850)
Chicago 2850
Store(store_id='S01', city='Chicago', region='North', size_sqm=2900)
{'store_id': 'S01', 'city': 'Chicago', 'region': 'North', 'size_sqm': 2850}

A named tuple is still a tuple: it is immutable, you can index and unpack it, and it uses as little memory as a plain tuple. _replace() returns a new record with some fields changed. _asdict() turns it into a dict, for example to write JSON. The leading underscore is there only to avoid clashes with your own field names. Module 21 compares namedtuple with typing.NamedTuple and dataclasses.

Iterators and itertools: chain, islice and batched

Section titled “Iterators and itertools: chain, islice and batched”

An iterator is an object that hands out the items of a stream one at a time and remembers its position. A for loop over a file uses an iterator: it reads one line, then the next. An iterator is used up after one pass. Module 10 explains how iterators work inside.

The itertools module is a set of building blocks that take iterables and return iterators. They are lazy: they produce each item only when the loop asks for it. A lazy tool can process a file that does not fit in memory. To see all items at once, wrap the iterator in list().

from itertools import batched, chain, islice
jan = ["O006743", "O006750"]
feb = ["O007200"]
mar = ["O007626", "O007633"]
print(list(chain(jan, feb, mar)))
print(list(islice(chain(jan, feb, mar), 1, 4)))
Output
['O006743', 'O006750', 'O007200', 'O007626', 'O007633']
['O006750', 'O007200', 'O007626']

chain(a, b, c) walks through a, then b, then c, as one stream, without building a new list. islice(iterable, start, stop) takes a slice of any iterable, including a file or a chain, which you cannot index. Here it takes items 1 to 3.

batched(iterable, n) (Python 3.12+) cuts a stream into tuples of n items. Use it to send rows to a database or an API in chunks:

customer_ids = [f"C{number:05d}" for number in range(1, 12)]
for batch in batched(customer_ids, 4):
print(batch)
Output
('C00001', 'C00002', 'C00003', 'C00004')
('C00005', 'C00006', 'C00007', 'C00008')
('C00009', 'C00010', 'C00011')

The last batch is shorter. From Python 3.13, batched(..., strict=True) raises a ValueError instead, for when every batch must be full.

itertools: accumulate, pairwise and groupby

Section titled “itertools: accumulate, pairwise and groupby”

These three tools answer the questions of a monthly report: what is the total so far, how much did it change, and what is the sum per group.

from itertools import accumulate, pairwise
monthly = [14162.33, 4719.04, 12296.72, 10879.04, 6675.86, 8533.40] # data/reports
print([round(total, 2) for total in accumulate(monthly)])
print(list(accumulate([21.0, 21.9, 21.4, 22.1], max)))
for before, after in pairwise(monthly[:3]):
print(f"{before:>9,.2f} -> {after:>9,.2f} {(after - before) / before:+.1%}")
Output
[14162.33, 18881.37, 31178.09, 42057.13, 48732.99, 57266.39]
[21.0, 21.9, 21.9, 22.1]
14,162.33 -> 4,719.04 -66.7%
4,719.04 -> 12,296.72 +160.6%

accumulate() gives running totals: the year-to-date revenue after each month. With a second argument it applies any two-argument function instead of +: max gives the running maximum. pairwise() gives each item with the next one: (m1, m2), (m2, m3) and so on. That is the shape of every month-over-month change.

groupby(iterable, key) groups consecutive items that have the same key. It yields one (key, group) pair per run, where group is an iterator over the items of that run.

from itertools import groupby
statuses = ["ok", "ok", "warn", "warn", "warn", "ok", "fail", "ok", "ok"]
print([(status, len(list(run))) for status, run in groupby(statuses)])
Output
[('ok', 2), ('warn', 3), ('ok', 1), ('fail', 1), ('ok', 2)]

"ok" appears three times, because it forms three separate runs. To group a whole dataset by a key, sort it by the same key first. To find runs, such as three warn readings in a row, do not sort.

The operator module turns operators and lookups into functions. itemgetter("store_id") is a function that returns row["store_id"]. It is a short, fast replacement for lambda row: row["store_id"]:

from operator import itemgetter
lines = [
{"store_id": "S11", "revenue": 66.49},
{"store_id": "S10", "revenue": 14.99},
{"store_id": "S11", "revenue": 59.99},
{"store_id": "S05", "revenue": 19.99},
]
lines.sort(key=itemgetter("store_id"))
for store_id, group in groupby(lines, key=itemgetter("store_id")):
print(store_id, round(sum(row["revenue"] for row in group), 2))
Output
S05 19.99
S10 14.99
S11 126.48

After the sort, both S11 lines are neighbors, so groupby puts them in one group. attrgetter("city") does the same for attributes, such as the fields of a named tuple.

Model tuning tries every combination of a few settings: this is a grid search. product() builds the grid: the Cartesian product of the value lists, every way to pick one value from each list. combinations() picks unordered groups of items, such as every pair of stores to compare. permutations() picks ordered arrangements.

import math
from itertools import combinations, permutations, product
grid = list(product([0.01, 0.1], [3, 5, 7])) # learning rate x tree depth
print(len(grid), grid[:3])
north = ["S01", "S02", "S03"]
print(list(combinations(north, 2)))
print(len(list(permutations(north, 2))), math.comb(12, 2))
Output
6 [(0.01, 3), (0.01, 5), (0.01, 7)]
[('S01', 'S02'), ('S01', 'S03'), ('S02', 'S03')]
6 66

product(a, b) gives every (x, y) with x from a and y from b: 2 × 3 = 6 settings. combinations(north, 2) gives each pair once, because ("S01", "S02") and ("S02", "S01") are the same pair. permutations counts both orders. math.comb(12, 2) says that the 12 stores form 66 pairs. Grids grow fast: 4 settings with 5 values each are 625 models.

partial(func, ...) returns a new function with some arguments already filled in. Use it when a tool expects a one-argument function, but your function needs settings.

from functools import partial, reduce
def in_range(value, low, high):
return low <= value <= high
temperature_ok = partial(in_range, low=19.0, high=23.0)
readings = [21.0, 23.4, 22.1, 18.7]
print(temperature_ok(21.7))
print(list(filter(temperature_ok, readings)))
print(temperature_ok.func.__name__, temperature_ok.keywords)
Output
True
[21.0, 22.1]
in_range {'low': 19.0, 'high': 23.0}

temperature_ok is in_range with low and high fixed. A closure (module 05) could do the same, but partial is shorter and shows its settings in .func and .keywords.

reduce(func, iterable, initial) folds a sequence into one value. It calls func(accumulator, item) for each item and keeps the result as the new accumulator.

flowchart LR
    I["initial 1.0"] --> A["f(1.0, 0.05)"]
    A --> B["f(1.05, -0.02)"]
    B --> C["f(1.029, 0.10)"]
    C --> R["result 1.1319"]
growth = [0.05, -0.02, 0.10] # monthly revenue growth rates
factor = reduce(lambda acc, rate: acc * (1 + rate), growth, 1.0)
print(round(factor, 4), round(math.prod(1 + rate for rate in growth), 4))
store_products = [{"P001", "P010", "P014"}, {"P001", "P014", "P021"}, {"P014", "P001"}]
print(sorted(reduce(set.intersection, store_products)))
Output
1.1319 1.1319
['P001', 'P014']

Three months of growth multiply into a factor of 1.1319: +13.19% in total. math.prod() says the same more clearly. Prefer a built-in such as sum, max, math.prod or "".join when one exists. Use reduce when no built-in exists, for example to intersect many sets: products sold in every store.

A cache stores results so that you do not compute them twice. Caching the results of a function by its arguments is called memoization. It pays off for slow calls that repeat: a lookup in a file, a request to an API, a recursive formula.

The line @lru_cache(maxsize=2) above a function is a decorator: it wraps the function in a new one that adds a behavior, here the cache. Module 11 shows how decorators work inside. Here you only use them.

from functools import cache, lru_cache
@lru_cache(maxsize=2)
def exchange_rate(currency):
print(" fetching", currency) # stands for a slow API call
return {"EUR": 0.92, "GBP": 0.79, "CAD": 1.36}[currency]
for currency in ["EUR", "EUR", "GBP", "EUR", "CAD", "GBP"]:
print(currency, exchange_rate(currency))
print(exchange_rate.cache_info())
Output
fetching EUR
EUR 0.92
EUR 0.92
fetching GBP
GBP 0.79
EUR 0.92
fetching CAD
CAD 1.36
fetching GBP
GBP 0.79
CacheInfo(hits=2, misses=4, maxsize=2, currsize=2)

A “fetching” line means a real call, a miss. A line without it was answered from the cache, a hit. LRU means “least recently used”: when the cache is full, it drops the entry that was used longest ago. CAD pushed out GBP, so the last GBP call was a miss again.

@cache is lru_cache(maxsize=None): it never drops anything. Use it when the number of distinct arguments is small, such as 12 store ids. Three rules:

  1. Cache only pure functions: the same arguments always give the same result, with no side effects. A cached print runs only once.
  2. Arguments must be hashable (module 04): str, int, tuples. A list argument raises TypeError: unhashable type: 'list'.
  3. A cached result can go stale. Call func.cache_clear() when the source data changes.

Dates in files are text: "2024-05-01", "07/01/2023", "January 7, 2023". To sort, subtract or group dates, convert the text into date objects. The datetime module has four main types:

Type Holds Example
date a calendar day date(2024, 5, 1)
time a clock time time(8, 25, 13)
datetime a day and a clock time datetime(2024, 5, 1, 8, 25, 13)
timedelta a duration timedelta(days=1, minutes=10)

ISO 8601 is the international standard for dates and times: 2024-05-01T08:25:13, largest unit first. ISO strings sort correctly as text, and fromisoformat() reads them directly. For other layouts, strptime(text, format) (“string parse time”) reads the text with a format, and strftime(format) (“string format time”) writes it.

from datetime import date, datetime, timedelta
opened = date.fromisoformat("2023-06-15") # store S12 in data/stores.csv
print(opened, opened.year, opened.strftime("%A %d %B %Y"))
print((opened - date(2023, 1, 1)).days, "days after the first sale")
stamp = datetime.strptime("07/01/2023 14:05", "%d/%m/%Y %H:%M") # day first
print(stamp, stamp.isoformat(), stamp.weekday())
print(datetime.fromisoformat("2024-05-01 08:04:01,354")) # a log timestamp
Output
2023-06-15 2023 Thursday 15 June 2023
165 days after the first sale
2023-01-07 14:05:00 2023-01-07T14:05:00 5
2024-05-01 08:04:01.354000

date - date gives a timedelta. .days reads its whole days. weekday() counts from Monday = 0, so 5 is a Saturday. Since Python 3.11, fromisoformat() reads most ISO 8601 forms, including the comma before the milliseconds that the log uses.

Code Meaning Example
%Y / %m / %d year, month, day (zero-padded) 2024, 05, 01
%H / %M / %S hour (24 h), minute, second 08, 25, 13
%f microseconds (reads 1 to 6 digits) 354000
%B / %b month name, short month name January, Jan
%A / %a weekday name, short weekday name Sunday, Sun
%j day of the year 001–366
%z UTC offset -0500

Arithmetic with timedelta replaces the // and % work of module 01. Dividing two durations counts how many times one fits in the other:

start = datetime(2024, 5, 1) # first reading in data/sensors.csv
interval = timedelta(minutes=10)
print(start + 1000 * interval)
print((datetime(2024, 5, 9, 15, 20) - start) // interval)
print(timedelta(hours=1, minutes=30).total_seconds())
Output
2024-05-07 22:40:00
1244
5400.0

Reading 1000 falls on 2024-05-07 at 22:40, as module 01 worked out by hand. // between two durations gives a whole number of intervals.

Time zones and daylight saving time with zoneinfo

Section titled “Time zones and daylight saving time with zoneinfo”

A datetime without time-zone information is naive: 08:25 could be Chicago time or Berlin time. A datetime with a tzinfo is aware: it names one exact moment. UTC (Coordinated Universal Time) is the reference clock with no offset and no seasonal changes. A UTC offset is the difference between a local clock and UTC, such as −05:00.

A time zone is a set of rules for the offset of one region, including its daylight saving time (DST): clocks move one hour forward in spring and back in autumn. The rules live in the IANA time-zone database, under names such as America/Chicago. zoneinfo.ZoneInfo(name) loads them.

from datetime import UTC
from zoneinfo import ZoneInfo
logged = datetime(2024, 5, 1, 13, 25, tzinfo=UTC)
print(logged.isoformat())
print(logged.astimezone(ZoneInfo("America/Chicago")))
print(logged.astimezone(ZoneInfo("Asia/Kolkata")).isoformat())
Output
2024-05-01T13:25:00+00:00
2024-05-01 08:25:00-05:00
2024-05-01T18:55:00+05:30

astimezone() shows the same moment on another clock. Chicago is 5 hours behind UTC in May (daylight time), and India is 5 hours 30 minutes ahead. datetime.UTC (Python 3.11+) is the UTC time zone.

DST makes some local days 23 or 25 hours long. On 2024-03-10, New York clocks jumped from 02:00 to 03:00:

new_york = ZoneInfo("America/New_York")
before = datetime(2024, 3, 9, 12, 0, tzinfo=new_york)
after = datetime(2024, 3, 10, 12, 0, tzinfo=new_york)
print(before.tzname(), after.tzname())
print(after - before)
print(after.astimezone(UTC) - before.astimezone(UTC))
Output
EST EDT
1 day, 0:00:00
23:00:00

EST is standard time (UTC−5) and EDT is daylight time (UTC−4). Between noon and noon, only 23 real hours passed. But Python subtracts two datetimes of the same time zone as wall-clock times, so it says 1 day. Converted to UTC, the difference is the real 23 hours. The rule that avoids this whole class of bugs: store and compute times in UTC; convert to local time only to show them.

A regular expression (regex) is a small pattern language for text. \d{3} means “three digits”. One pattern can find, check, extract or replace text that string methods handle only with many steps. The re module runs patterns.

Write every pattern as a raw string (module 02): r"\d{3}". In a normal string, Python itself reads some backslash codes first. "\b" is a backspace character, but in a regex \b means a word boundary.

import re
print(len("\b"), len(r"\b"))
Output
1 2

The building blocks:

Pattern Matches Example
. any character except a line break a.c matches abc
\d, \w, \s a digit, a word character (letter, digit, _), a whitespace character \d\d matches 42
\D, \W, \S the opposite: not a digit, and so on \S+ matches user=-
[abc], [^abc], [A-Z] one character from a set, not from a set, from a range [45]\d\d matches 404
*, +, ? 0 or more, 1 or more, 0 or 1 of the previous item \d+
{3}, {2,4} exactly 3, between 2 and 4 \d{4} matches 2024
^, $ start and end of the text ^\d{4}
\b a word boundary \bERROR\b
(...) a capturing group (\d+)ms
(?P<name>...) a named group (?P<ms>\d+)ms
a|b a or b GET|POST
\., \[ a literal . or [ \[api\]

The main functions:

Function Returns
re.search(p, text) the first match anywhere, or None
re.match(p, text) a match at the start of the text only, or None
re.fullmatch(p, text) a match only if the whole text matches, or None
re.findall(p, text) a list of all matches (strings, or tuples of groups)
re.finditer(p, text) an iterator of match objects
re.sub(p, repl, text) the text with every match replaced
re.split(p, text) the text split at every match
re.compile(p, flags) a pattern object with the same methods

A match object holds the matched text, its position and its groups: the parts of the pattern in parentheses.

line = (
"2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 "
"POST /api/v1/predict 201 93ms user=mei.chen@example.org"
)
match = re.search(r"(\d{3}) (\d+)ms", line)
print(match.group(0), "|", match.group(1), "|", match.group(2))
print(match.groups(), match.start())
Output
201 93ms | 201 | 93
('201', '93') 67

group(0) is the whole match. group(1) and group(2) are the parentheses, numbered from the left. Groups are always strings: convert them with int(). A named group (?P<name>...) gives a part a name, so the code says what it extracts. re.compile() turns a pattern into a reusable object. Flags change how a pattern matches. re.VERBOSE allows spaces, line breaks and # comments inside the pattern, so a long pattern stays readable:

API_REQUEST = re.compile(
r"""
(?P<method>GET|POST)\s # HTTP method
(?P<path>\S+)\s # path, up to the next space
(?P<status>\d{3})\s # status code
(?P<ms>\d+)ms # duration in milliseconds
""",
re.VERBOSE,
)
request = API_REQUEST.search(line)
print(request["method"], request["path"], int(request["status"]), int(request["ms"]))
print(request.groupdict())
Output
POST /api/v1/predict 201 93
{'method': 'POST', 'path': '/api/v1/predict', 'status': '201', 'ms': '93'}

request["status"] is short for request.group("status"). groupdict() returns all named groups as a dict, ready to become a record.

findall() returns every match. With no groups, it returns the matched strings. With groups, it returns the groups instead:

note = "Refund O000017 and O000101; ignore order O12."
print(re.findall(r"O\d{6}", note))
print(re.findall(r"O(\d{6})", note))
print(re.findall(r"error", "ERROR at load; error in clean", flags=re.IGNORECASE))
Output
['O000017', 'O000101']
['000017', '000101']
['ERROR', 'error']

O12 has only 2 digits, so \d{6} skips it. re.IGNORECASE ignores upper and lower case. re.MULTILINE makes ^ and $ match at every line of a multi-line text, not just at its start and end.

sub() replaces each match. In the replacement, \1 inserts group 1 of the match. This masks the personal data in a log line before you share it:

print(re.sub(r"user=\S+", "user=***", line))
print(re.sub(r"(\w)[\w.]*@", r"\1***@", "mei.chen@example.org"))
Output
2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=***
m***@example.org

A quantifier (*, +, ?, {m,n}) says how many times the item before it may repeat. Quantifiers are greedy: they take as many characters as they can. Add ? to make them lazy: as few as possible.

print(re.findall(r"\[.*\]", "[api] [cache]"))
print(re.findall(r"\[.*?\]", "[api] [cache]"))
print(re.match(r"INFO", line), re.fullmatch(r"P\d{3}", "P001") is not None)
Output
['[api] [cache]']
['[api]', '[cache]']
None True

The greedy .* ran to the last ] and swallowed both brackets. match() failed because the line starts with the date, not with INFO. fullmatch() is the right tool to validate a whole value, such as a product id.

These three modules cover quick numeric work without NumPy.

math has the functions of a scientific calculator, plus some for data work:

print(math.sqrt(2850), math.ceil(250 / 12), math.floor(-3.5))
print(math.log(1000, 10), math.log10(1000), round(math.exp(1), 5))
print(sum([0.1] * 10), math.fsum([0.1] * 10))
print(math.isnan(float("nan")), float("nan") == float("nan"), math.inf > 10**100)
Output
53.38539126015655 21 -4
2.9999999999999996 3.0 2.71828
1.0 1.0
True False True

log(x, base) computes through natural logs and can miss the exact answer by one bit. log10 and log2 are exact for powers of their base. fsum() adds floats with no rounding build-up. NaN (“not a number”) is the float that marks a missing or undefined result. It is not equal to anything, not even itself, so test it with math.isnan().

statistics summarizes a list of numbers. The sample standard deviation ss measures how far values spread around the mean xˉ\bar{x}:

s=1n−1∑i=1n(xi−xˉ)2s = \sqrt{\frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \bar{x})^2}

stdev() divides by n−1n - 1, for a sample of a larger population. pstdev() divides by nn, when the data is the whole population. pandas .std() uses n−1n - 1 too.

import statistics
readings = [21.0, 21.9, 21.4, 21.7, 22.1, 21.4] # °C
mean = statistics.mean(readings)
print(round(mean, 2), round(statistics.median(readings), 2), statistics.mode(readings))
print(round(statistics.stdev(readings), 3), round(statistics.pstdev(readings), 3))
print([round(cut, 2) for cut in statistics.quantiles(readings, n=4)])
Output
21.58 21.55 21.4
0.397 0.362
[21.3, 21.55, 21.95]

The median of an even number of values is the mean of the two middle values: (21.4 + 21.7) / 2. Floats such as 21.549999999999997 appear in raw results, so the code rounds them for display. quantiles(data, n=4) returns the three cut points that split the data into four equal parts: the quartiles. mode() returns the most common value. statistics also has fmean() (a fast float mean), correlation(), linear_regression() and NormalDist.

random makes pseudo-random numbers: numbers that look random but come from a formula that starts from a seed. The same seed always gives the same sequence. Create your own generator with random.Random(42), as NumPy’s default_rng(42) does later in the course:

import random
rng = random.Random(42)
print(rng.random(), rng.randint(1, 6))
print(rng.choice(["S01", "S02", "S03"]), rng.sample(range(1, 5001), 3))
print(rng.choices(["store", "online"], weights=[58, 42], k=6))
print(round(rng.gauss(mu=60.84, sigma=10), 2))
Output
0.6394267984578837 1
S03 [2254, 2007, 1829]
['store', 'store', 'online', 'store', 'online', 'store']
66.89

random() gives a float in [0, 1). randint(a, b) includes both ends. sample() draws without replacement (no repeats). choices() draws with replacement, with optional weights. shuffle(list) reorders a list in place. The functions at module level, such as random.random(), share one hidden generator for the whole program. Any library that draws from it shifts your sequence. Your own Random(42) instance is yours alone. For passwords and tokens use the secrets module, because a seeded generator is predictable.

os talks to the operating system. Its most useful part for data work is os.environ, the environment variables: name–value settings that every process inherits from the program that started it. Deployment tools set them to pass settings and secrets to a program without putting them in the code.

import os
import shutil
import sys
from pathlib import Path
print(os.environ.get("REPORT_DIR", "output")) # a default when it is not set
os.environ["REPORT_DIR"] = "output/backup" # this process and its children
target = Path(os.environ["REPORT_DIR"])
target.mkdir(parents=True, exist_ok=True)
copied = shutil.copy2("data/reports/2024-01.csv", target)
print(Path(copied).as_posix(), Path(copied).stat().st_size)
Output
output
output/backup/2024-01.csv 3014

os.environ behaves like a dict of strings. get() with a default keeps the script working when the variable is not set. Values are always strings: convert "3" with int(). shutil (“shell utilities”) copies and moves files:

Call Does
shutil.copy(src, dst) copies the content (dst may be a folder)
shutil.copy2(src, dst) copies the content and the metadata, such as the modification time
shutil.copytree(src, dst, dirs_exist_ok=True) copies a whole folder
shutil.move(src, dst) moves or renames a file or folder
shutil.rmtree(path) deletes a folder and everything in it, with no undo
shutil.make_archive(base, "zip", root_dir) writes base.zip from a folder
shutil.which("git") finds a program on the PATH, or None

sys talks to the running interpreter:

Name Holds
sys.argv the command-line words; sys.argv[0] is the script name (module 08)
sys.executable the path of the Python that runs this script
sys.version_info the version, for checks such as sys.version_info >= (3, 12)
sys.platform "darwin", "linux" or "win32"
sys.path the folders that import searches (module 08)
sys.stdout, sys.stderr the output and error streams
sys.exit(code) ends the program with an exit code (module 08): 0 means success
print(sys.version_info >= (3, 12), sys.platform in {"darwin", "linux", "win32"})
Output
True True

Paths, versions and platforms differ between machines, so scripts compare them instead of printing them. For paths, prefer pathlib (module 07) to the older os.path functions.

subprocess.run() starts another program, waits for it and returns a CompletedProcess object. Pass the command as a list of words. The first word is the program. sys.executable is the path of the current Python, so the child runs in the same environment.

import subprocess
result = subprocess.run(
[sys.executable, "-c", "print(sum(range(1, 101)))"],
capture_output=True,
text=True,
check=True,
)
print(result.returncode, result.stdout.strip(), repr(result.stderr))
Output
0 5050 ''

capture_output=True collects the child’s output instead of showing it. text=True decodes it to str. check=True raises CalledProcessError when the exit code is not 0, so a failed step cannot pass in silence:

try:
subprocess.run(
[sys.executable, "-c", "import sys; sys.exit('bad input')"],
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError as error:
print("exit code:", error.returncode, "| stderr:", error.stderr.strip())
Output
exit code: 1 | stderr: bad input

sys.exit("message") prints the message to stderr and exits with code 1. A list of words never goes through a shell, the program that reads terminal commands. That matters: with shell=True and a string built from user input, a value such as "x; rm -rf ~" runs a second command. This attack is called shell injection. Add timeout=60 to stop a child that hangs.

Task Tool Instead of
count items Counter d[k] = d.get(k, 0) + 1
group records under a key defaultdict(list) if k not in d: d[k] = []
keep the last n values deque(maxlen=n) list.append() plus pop(0)
a light, read-only record namedtuple a tuple with magic indexes
join several iterables chain a + b + c (copies everything)
first n items of a file or iterator islice a counter and break
fixed-size chunks batched slicing with range(0, len, n)
running total or maximum accumulate a loop with an accumulator
each item with the next pairwise zip(xs, xs[1:])
runs of equal values, or groups of sorted data groupby a loop that tracks the previous key
every combination of settings product, combinations nested loops
a function with fixed settings partial a lambda or a closure
repeated slow calls cache, lru_cache a hand-written dict of results
dates and durations datetime, timedelta string slicing and //
time zones zoneinfo fixed offsets such as −5 hours
text patterns re chains of find() and split()
summary statistics statistics hand-written formulas
reproducible random samples random.Random(42) the global random functions
settings and secrets os.environ values typed into the code
copy and archive files shutil reading and writing bytes yourself
run another program subprocess.run([...], check=True) os.system("...")

Example 1 — Summarize a month of sales with collections

Section titled “Example 1 — Summarize a month of sales with collections”

Goal: A store manager wants a January 2024 summary from data/sales.csv: the best-selling products by units, and the orders and revenue of each region.

Step 1 — Load the January lines as named tuples

Section titled “Step 1 — Load the January lines as named tuples”
import csv
Line = namedtuple("Line", ["order_id", "region", "product", "quantity", "revenue"])
january = []
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024-01"):
january.append(
Line(row["order_id"], row["region"], row["product"],
int(row["quantity"]), float(row["revenue"]))
)
print(len(january))
print(january[0])
Output
654
Line(order_id='O006722', region='West', product='Organic Cotton T-Shirt', quantity=1, revenue=18.99)

ISO dates start with the year and month, so startswith("2024-01") selects January 2024. Each row becomes a Line with converted types. Later code writes line.quantity instead of row["quantity"] plus a conversion.

units = Counter()
for line in january:
units[line.product] += line.quantity
for name, count in units.most_common(3):
print(f"{name:<25}{count:>4}")
print(len(units), "products,", units.total(), "units")
Output
Running Socks 3-Pack 61
Organic Cotton T-Shirt 60
Harbor Lane Mysteries 58
28 products, 943 units

Counter(line.product for line in january) would count lines, not units. Adding line.quantity weights each line by its units. most_common(3) sorts by count for you.

Step 3 — Group orders and revenue by region

Section titled “Step 3 — Group orders and revenue by region”
orders = defaultdict(set)
revenue = defaultdict(float)
for line in january:
orders[line.region].add(line.order_id)
revenue[line.region] += line.revenue
print({region: len(ids) for region, ids in orders.items()})
Output
{'West': 126, 'North': 112, 'East': 132, 'South': 104}

One order can have up to 3 lines. A set keeps each order id once, so len() counts orders, not lines. The two defaultdicts fill in one pass over the data.

print(f"{'Region':<8}{'Orders':>7}{'Revenue':>12}{'Per order':>11}")
for region in sorted(revenue, key=revenue.get, reverse=True):
count, total = len(orders[region]), revenue[region]
print(f"{region:<8}{count:>7}{total:>12,.2f}{total / count:>11.2f}")
Output
Region Orders Revenue Per order
West 126 38,269.90 303.73
East 132 29,277.14 221.80
South 104 28,094.60 270.14
North 112 23,955.25 213.89

sorted(revenue, key=revenue.get, reverse=True) sorts the region names by their revenue, largest first. West has fewer orders than East but more revenue, so its average order is larger.

Common mistakes:

  • Counting lines when the question is about units. Add the quantity, as in Step 2.
  • Counting order lines as orders. Collect the order ids in a set first.
  • Printing a defaultdict directly. It prints as defaultdict(<class 'set'>, {...}). Convert it with dict() first, or loop over it.

Example 2 — Watch a rolling window of sensor readings with deque

Section titled “Example 2 — Watch a rolling window of sensor readings with deque”

Goal: Sensor S4 in data/sensors.csv wears out from May 12 and its vibration rises. Raise an alarm when the vibration of the last hour (6 readings) stays above the warning level of 4.5 mm/s, without false alarms from single spikes.

Reading = namedtuple("Reading", ["timestamp", "vibration"])
s4 = []
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["sensor_id"] == "S4" and row["vibration_mm_s"]:
s4.append(Reading(row["timestamp"], float(row["vibration_mm_s"])))
print(len(s4), s4[0])
Output
2009 Reading(timestamp='2024-05-01T00:00:00', vibration=2.17)

S4 has 2,016 readings, and 7 of them have a blank vibration cell. and row["vibration_mm_s"] skips them, because an empty string is falsy.

single = Counter(r.timestamp[:10] for r in s4 if r.vibration >= 4.5)
print(len(single), "days with alarms")
print(sorted(single.items())[:4])
Output
13 days with alarms
[('2024-05-01', 4), ('2024-05-02', 2), ('2024-05-03', 2), ('2024-05-04', 1)]

A rule on one reading fires on 13 of the 14 days. The sensor is healthy before May 12: these are spikes, short jumps of 3 to 5 times the normal level.

Step 3 — Compare a rolling mean with a rolling median

Section titled “Step 3 — Compare a rolling mean with a rolling median”
def alarm_days(readings, summary, size=6, limit=4.5):
window = deque(maxlen=size)
days = Counter()
for reading in readings:
window.append(reading.vibration)
if len(window) == size and summary(window) > limit:
days[reading.timestamp[:10]] += 1
return days
mean_days = alarm_days(s4, statistics.mean)
median_days = alarm_days(s4, statistics.median)
for name, days in [("mean", mean_days), ("median", median_days)]:
print(f"{name:<7}{len(days)} days:", ", ".join(day[5:] for day in sorted(days)))
Output
mean 9 days: 05-01, 05-02, 05-03, 05-04, 05-05, 05-07, 05-12, 05-13, 05-14
median 3 days: 05-12, 05-13, 05-14

The deque always holds the last 6 readings. On May 1 at 08:00, the window is 2.82, 2.77, 3.11, 2.99, 3.18 and one spike of 12.92 mm/s. That single spike lifts the mean to 4.63, so the mean rule raises false alarms on 6 quiet days. The median is the middle value, so one or two spikes cannot move it. The median rule fires only on the three days of real wear. Passing the summary function as an argument (module 05) lets one loop test both rules.

window = deque(maxlen=6)
for reading in s4:
window.append(reading.vibration)
if len(window) == 6 and statistics.median(window) > 4.5:
print(reading.timestamp, [round(v, 1) for v in window])
break
Output
2024-05-12T02:40:00 [5.0, 4.1, 4.8, 5.2, 3.7, 5.2]

The window holds six readings between 3.7 and 5.2 mm/s, with a median of 4.9: a steady rise, not a spike. A maintenance team gets this alarm in the early morning of May 12.

Common mistakes:

  • Computing the rule before the window is full. The first values average fewer readings. Check len(window) == size.
  • Using a list and pop(0) on a long stream. It works, but each pop(0) moves every item. deque(maxlen=...) drops the oldest value by itself.
  • Smoothing with a mean when the data has spikes. A median, or a rule such as “4 of the last 6 readings”, is robust to spikes.

Example 3 — Build a half-year revenue report with itertools

Section titled “Example 3 — Build a half-year revenue report with itertools”

Goal: Combine the six monthly extracts in data/reports/ into one report: revenue per month, the running total and the change from the month before. Then send the rows to a warehouse in batches.

Step 1 — Chain the six files into one stream

Section titled “Step 1 — Chain the six files into one stream”
def read_rows(path):
with open(path, encoding="utf-8", newline="") as f:
yield from csv.DictReader(f)
paths = sorted(Path("data/reports").glob("*.csv"))
rows = chain.from_iterable(read_rows(path) for path in paths)
for row in islice(rows, 2):
print(row["order_id"], row["order_date"], row["product"], row["revenue"])
Output
O006743 2024-01-02 Organic Cotton T-Shirt 39.98
O006750 2024-01-03 Fitness Tracker 99.99

read_rows() is a small generator function: yield from hands out the rows of one file one at a time, and the file closes after the last row. Module 10 explains generators. chain.from_iterable() takes an iterable of iterables, here one row stream per file. islice(rows, 2) peeks at two rows; nothing else is read yet. csv.DictReader matches columns by name, so the different column order of 2024-04.csv does no harm.

Step 2 — See that an iterator is used up

Section titled “Step 2 — See that an iterator is used up”
rest = list(rows)
print(len(rest), len(list(rows)))
Output
295 0

The islice in Step 1 took 2 rows, so the rest of the stream holds 295 of the 297 rows. A second list(rows) is empty: the iterator is used up. To make a second pass, build a new stream.

Step 3 — Sum revenue per month with groupby

Section titled “Step 3 — Sum revenue per month with groupby”
def month_of(row):
return row["order_date"][:7] # "2024-01"
rows = chain.from_iterable(read_rows(path) for path in paths)
months = []
for month, group in groupby(rows, key=month_of):
months.append((month, sum(float(row["revenue"]) for row in group)))
print(months[:2])
Output
[('2024-01', 14162.33), ('2024-02', 4719.04)]

The files are in date order and each file is sorted by date, so the stream is already sorted by month. groupby can group it without a sort. month_of is the key function: it returns the YYYY-MM part of the date.

Step 4 — Add the running total and the change

Section titled “Step 4 — Add the running total and the change”
revenues = [revenue for _, revenue in months]
changes = [None] + [(after - before) / before for before, after in pairwise(revenues)]
print(f"{'Month':<9}{'Revenue':>11}{'YTD':>11}{'Change':>9}")
for (month, value), ytd, change in zip(months, accumulate(revenues), changes):
shown = "" if change is None else f"{change:+.1%}"
print(f"{month:<9}{value:>11,.2f}{ytd:>11,.2f}{shown:>9}")
Output
Month Revenue YTD Change
2024-01 14,162.33 14,162.33
2024-02 4,719.04 18,881.37 -66.7%
2024-03 12,296.72 31,178.09 +160.6%
2024-04 10,879.04 42,057.13 -11.5%
2024-05 6,675.86 48,732.99 -38.6%
2024-06 8,533.40 57,266.39 +27.8%

accumulate() gives the year-to-date total, and pairwise() gives one change per pair of months. January has no month before it, so the list of changes starts with None. zip() puts the three columns side by side.

Step 5 — Find the products sold every month and send batches

Section titled “Step 5 — Find the products sold every month and send batches”
per_month = [{row["product"] for row in read_rows(path)} for path in paths]
every_month = reduce(set.intersection, per_month)
print(len(every_month), sorted(every_month)[:3])
rows = chain.from_iterable(read_rows(path) for path in paths)
sizes = [len(batch) for batch in batched(rows, 100)]
print(sizes)
Output
8 ['2-Person Camping Tent', 'Air Purifier', 'Electric Toothbrush']
[100, 100, 97]

reduce(set.intersection, ...) intersects six sets: 8 products appear in every monthly extract. batched(rows, 100) yields tuples of 100 rows from a fresh stream. A real job would send each batch with one database or API call.

Common mistakes:

  • Reusing a used-up iterator. The second loop gets nothing and raises no error. Build a new stream, or store the rows in a list.
  • Calling groupby on unsorted data. You get one group per run of equal keys, not one per key.
  • Dividing by the first month on the first row. The first month has no change; show an empty cell.

Example 4 — Search a grid of churn rules with functools

Section titled “Example 4 — Search a grid of churn rules with functools”

Goal: A retention team flags customers for a call with a simple rule: tenure at most T months and at most L logins in the last 30 days. Find the T and L with the best F1 score on data/customers.csv, and load the file only once.

Customer = namedtuple("Customer", ["tenure", "logins", "churned"])
file_reads = 0
@cache
def load_customers(path="data/customers.csv"):
global file_reads
file_reads += 1
with open(path, encoding="utf-8", newline="") as f:
return tuple(
Customer(
int(r["tenure_months"]), int(r["logins_last_30d"]), r["churned"] == "1"
)
for r in csv.DictReader(f)
)
print(len(load_customers()), len(load_customers()), "file reads:", file_reads)
Output
5000 5000 file reads: 1

The second call returned the cached tuple: the file was read once. The function returns a tuple, not a list, because every caller gets the same cached object, and a tuple cannot be changed by mistake.

The rule is a classifier, so score it as one. Precision is the share of flagged customers who really churned. Recall is the share of churned customers that the rule flags. The F1 score is their harmonic mean: the reciprocal of the mean of the reciprocals. It is pulled toward the smaller value, so it is high only when both are high:

F1=2⋅precision⋅recallprecision+recallF_1 = \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}}
def rule_score(tenure_max, logins_max):
customers = load_customers()
flagged = [c.tenure <= tenure_max and c.logins <= logins_max for c in customers]
true_pos = sum(f and c.churned for f, c in zip(flagged, customers))
precision = true_pos / sum(flagged)
recall = true_pos / sum(c.churned for c in customers)
return 2 * precision * recall / (precision + recall)
print(f"{rule_score(6, 3):.3f}")
Output
0.120

True counts as 1 in sum(), so sum(flagged) is the number of flagged customers. The rule of module 01 (tenure ≤ 6 and logins ≤ 3) has an F1 of only 0.120. It flags just 90 customers. 70% of them churn (high precision), but they are only 6.5% of all churners (low recall).

grid = list(product([3, 6, 12, 24], [3, 5, 10]))
scores = {params: rule_score(*params) for params in grid}
best = max(scores, key=scores.get)
print(len(grid), "rules; best:", best, round(scores[best], 3))
print("file reads:", file_reads, load_customers.cache_info())
Output
12 rules; best: (12, 10) 0.379
file reads: 1 CacheInfo(hits=14, misses=1, maxsize=None, currsize=1)

product() builds the 12 rules and rule_score(*params) unpacks each pair into the two arguments. So far the code has asked for the data 15 times: twice in Step 1, once in Step 2 and 12 times in the grid. Only the first call read the file; the other 14 were cache hits. Without @cache, there would be 15 file reads, and 1,000 for a grid of 1,000 rules.

score_for_logins = partial(rule_score, 12) # fix tenure_max = 12
for logins_max, score in zip([3, 5, 10, 20], map(score_for_logins, [3, 5, 10, 20])):
print(f"logins <= {logins_max:>2}: F1 {score:.3f}")
Output
logins <= 3: F1 0.180
logins <= 5: F1 0.260
logins <= 10: F1 0.379
logins <= 20: F1 0.443

partial(rule_score, 12) fixes the first positional argument, so score_for_logins(5) means rule_score(12, 5). map() needs a one-argument function, and partial builds it. The score keeps rising past 10 logins, the largest value in the grid. A grid only finds the best of the values you give it, so check the edges of the grid.

Common mistakes:

  • Caching a function that returns a mutable object, such as a list. A caller that changes it changes the cache for everybody. Return a tuple.
  • Caching a function whose data changes. Call load_customers.cache_clear() after the file changes.
  • Choosing the best rule on the same data that reports its score. Module 34 splits the data into a training and a test set, so the score is honest.

Example 5 — Time the pipeline runs and convert time zones

Section titled “Example 5 — Time the pipeline runs and convert time zones”

Goal: The pipeline server writes data/logs/app.log in UTC. Measure how long each pipeline run took, show the start times for the Chicago team, and schedule tomorrow’s runs across a DST change.

Step 1 — Parse the start and finish lines

Section titled “Step 1 — Parse the start and finish lines”
starts, finishes = {}, {}
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f:
if "[pipeline]" not in line:
continue
stamp = datetime.fromisoformat(line[:23]).replace(tzinfo=UTC)
run_id = re.search(r"run-\d{4}", line).group()
(starts if "Starting" in line else finishes)[run_id] = stamp
print(len(starts), len(finishes))
print(starts["run-0001"].isoformat(timespec="milliseconds"))
Output
9 9
2024-05-01T08:25:13.663+00:00

The first 23 characters of a line are its timestamp. replace(tzinfo=UTC) makes the naive datetime aware: the log is in UTC, and now the object says so. isoformat(timespec="milliseconds") shows three decimals and the +00:00 offset.

durations = {run: finishes[run] - starts[run] for run in starts}
for run in list(durations)[:3]:
print(run, durations[run], f"{durations[run].total_seconds():.3f} s")
seconds = [d.total_seconds() for d in durations.values()]
print(f"mean {statistics.mean(seconds):.2f} s, max {max(durations.values())}")
Output
run-0001 0:00:04.804000 4.804 s
run-0002 0:00:05.499000 5.499 s
run-0003 0:00:05.755000 5.755 s
mean 5.72 s, max 0:00:11.550000

Subtracting two aware datetimes in UTC gives the real elapsed time as a timedelta. total_seconds() turns it into a float for statistics. max() works on timedelta values directly, because durations compare like numbers.

Step 3 — Show the start times in Chicago

Section titled “Step 3 — Show the start times in Chicago”
chicago = ZoneInfo("America/Chicago")
for run in ["run-0001", "run-0009"]:
local = starts[run].astimezone(chicago)
print(run, local.strftime("%Y-%m-%d %H:%M %Z"), local.strftime("%z"))
Output
run-0001 2024-05-01 03:25 CDT -0500
run-0009 2024-05-01 12:07 CDT -0500

The 08:25 UTC run started at 03:25 Chicago time. %Z prints the abbreviation (CDT, Central Daylight Time) and %z the offset. The stored value stays in UTC. Only the display changes.

Step 4 — Schedule a daily 06:00 run across the DST change

Section titled “Step 4 — Schedule a daily 06:00 run across the DST change”
first_run = datetime(2024, 11, 2, 6, 0, tzinfo=chicago)
for day in range(3):
local = first_run + timedelta(days=day)
print(local.isoformat(), "=", local.astimezone(UTC).strftime("%H:%M UTC"))
Output
2024-11-02T06:00:00-05:00 = 11:00 UTC
2024-11-03T06:00:00-06:00 = 12:00 UTC
2024-11-04T06:00:00-06:00 = 12:00 UTC

Clocks in Chicago moved back one hour on 2024-11-03. Adding timedelta(days=1) to an aware datetime keeps the wall-clock time, so the job stays at 06:00 local time. In UTC it moves from 11:00 to 12:00. That is what a team wants for a daily job: the same local time every day. To add 24 real hours instead, convert to UTC, add, and convert back.

Common mistakes:

  • Mixing naive and aware datetimes. aware - naive raises TypeError: can't subtract offset-naive and offset-aware datetimes. Make every timestamp aware as you parse it.
  • Using a fixed offset such as timedelta(hours=-6) for Chicago. It is right in winter and wrong in summer. Use ZoneInfo.
  • Subtracting two local times around a DST change. Convert both to UTC first.

Example 6 — Parse the API log with regular expressions

Section titled “Example 6 — Parse the API log with regular expressions”

Goal: An on-call engineer wants an API health summary from data/logs/app.log: the status codes, the median latency per endpoint and the slowest requests, with emails masked before the report is shared.

LOG_LINE = re.compile(
r"""
^(?P<stamp>\S+\ \S+)\s # date and time with milliseconds
(?P<level>[A-Z]+)\s # INFO, WARNING, ...
\[api\]\s # only lines of the api component
(?P<ip>[\d.]+)\s
(?P<method>GET|POST)\s
(?P<path>\S+)\s
(?P<status>\d{3})\s
(?P<ms>\d+)ms\s
user=(?P<user>\S+)$
""",
re.VERBOSE,
)
sample = (
"2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 "
"GET /api/v1/reports/2024-04 200 87ms user=priya.nair@example.com"
)
test = LOG_LINE.match(sample)
print(test["level"], test["ip"], test["path"], test["user"])
Output
INFO 10.0.3.17 /api/v1/reports/2024-04 priya.nair@example.com

In verbose mode, spaces in the pattern are ignored, so a real space is written \ or \s. ^ and $ anchor the whole line: the pattern either explains the full line or does not match. Testing on one known line before the whole file saves time.

Step 2 — Match every API line and count the status codes

Section titled “Step 2 — Match every API line and count the status codes”
requests = []
with open("data/logs/app.log", encoding="utf-8") as f:
for raw in f:
found = LOG_LINE.match(raw.rstrip("\n"))
if found:
requests.append(found.groupdict())
print(len(requests), "API requests")
status_counts = Counter(r["status"] for r in requests)
print(" ".join(f"{code}:{n}" for code, n in sorted(status_counts.items())))
Output
391 API requests
200:250 201:77 304:10 400:11 401:7 404:13 422:7 429:13 500:3

Lines from other components, and the traceback lines, do not match, so match() returns None and the if skips them. 391 lines are API requests. groupdict() turns each match into a dict record.

def endpoint(path):
path = path.split("?")[0] # drop the query string
return re.sub(r"/(P\d{3}|\d{4}-\d{2})$", "/{id}", path)
latency = defaultdict(list)
for r in requests:
latency[endpoint(r["path"])].append(int(r["ms"]))
for name, values in sorted(latency.items(), key=lambda item: -len(item[1])):
print(f"{name:<24}{len(values):>4}{statistics.median(values):>7.0f} ms")
Output
/api/v1/products 113 40 ms
/api/v1/products/{id} 104 27 ms
/api/v1/predict 97 88 ms
/health 40 3 ms
/api/v1/reports/{id} 37 191 ms

/api/v1/products/P026 and /api/v1/products/P021 are one endpoint with different ids. re.sub() replaces the id at the end (P and 3 digits, or a month such as 2024-04) with {id}, so they group together. The median is robust to the few very slow requests.

Step 4 — List the slowest requests with masked emails

Section titled “Step 4 — List the slowest requests with masked emails”
slowest = sorted(requests, key=lambda r: int(r["ms"]), reverse=True)[:3]
for r in slowest:
masked = re.sub(r"^(\w)[\w.]*@", r"\1***@", r["user"])
print(r["stamp"], r["status"], f"{r['ms']:>5}ms", r["path"], masked)
log_text = Path("data/logs/app.log").read_text(encoding="utf-8")
ips = set(re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", log_text))
print(len(ips), "distinct IPs:", sorted(ips)[:3])
Output
2024-05-01 18:28:00,578 500 1334ms /api/v1/products?page=2 p***@example.com
2024-05-01 17:18:02,430 500 1188ms /api/v1/predict p***@example.com
2024-05-01 19:34:34,922 500 974ms /api/v1/products?page=2 t***@example.org
7 distinct IPs: ['10.0.3.17', '10.0.3.42', '172.16.4.9']

The mask keeps the first letter and the domain: enough to tell users apart, not enough to identify them. (?:...) is a non-capturing group: it groups \.\d{1,3} for the {3} without making findall return it. The IP addresses come from the private and documentation ranges.

Common mistakes:

  • Forgetting the r prefix. Some patterns still work by luck, but "\b" silently becomes a backspace.
  • Using .* where \S+ fits. A greedy .* can run past the field you want.
  • Using findall with groups and expecting whole matches. With groups it returns only the groups.

Example 7 — Bootstrap a confidence interval for an A/B test

Section titled “Example 7 — Bootstrap a confidence interval for an A/B test”

Goal: In data/ab_test.csv, the new checkout page (treatment) converts better than the old one (control). Estimate how sure we can be of the difference with a bootstrap: resample the data many times and look at the spread of the results.

groups = defaultdict(list)
with open("data/ab_test.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
groups[row["group"]].append(int(row["converted"]))
control, treatment = groups["control"], groups["treatment"]
print(len(control), len(treatment))
Output
5002 4998

Each list holds one 0 or 1 per user. The mean of such a list is the conversion rate: the share of users who bought.

Step 2 — Compute the observed difference

Section titled “Step 2 — Compute the observed difference”
rate_c, rate_t = statistics.fmean(control), statistics.fmean(treatment)
observed = rate_t - rate_c
diff_pp = observed * 100 # percentage points
print(f"control {rate_c:.2%}, treatment {rate_t:.2%}, difference {diff_pp:+.2f} pp")
Output
control 10.12%, treatment 11.66%, difference +1.55 pp

The treatment converts about 1.55 percentage points (pp) better: the difference of two rates, not a relative lift. Relative to the control rate, the lift is about 15%. But a different set of 10,000 users would give a different number. How much could it move?

rng = random.Random(42)
diffs = []
for _ in range(1000):
resample_t = rng.choices(treatment, k=len(treatment))
resample_c = rng.choices(control, k=len(control))
diffs.append(statistics.fmean(resample_t) - statistics.fmean(resample_c))
cuts = statistics.quantiles(diffs, n=40)
low, high = cuts[0], cuts[-1]
print(f"95% bootstrap interval: {low * 100:+.2f} to {high * 100:+.2f} pp")
Output
95% bootstrap interval: +0.27 to +2.71 pp

Each resample draws users with replacement: the same user can appear twice. That simulates a new sample from the same population. A percentile is the value below which that percentage of the data falls. quantiles(n=40) cuts the 1,000 differences into 40 parts, so the first cut is the 2.5th percentile and the last one the 97.5th. 95% of the resampled differences lie between them. This range is a 95% confidence interval: a range that, built this way, contains the true difference in about 95% of experiments. The interval does not contain 0, so the lift is unlikely to be pure chance.

Step 4 — Check with the normal approximation

Section titled “Step 4 — Check with the normal approximation”
var_c = rate_c * (1 - rate_c) / len(control)
var_t = rate_t * (1 - rate_t) / len(treatment)
se = math.sqrt(var_c + var_t)
z = statistics.NormalDist().inv_cdf(0.975)
print(f"se = {se:.4f}, z = {z:.3f}")
low_n, high_n = observed - z * se, observed + z * se
print(f"normal interval: {low_n * 100:+.2f} to {high_n * 100:+.2f} pp")
Output
se = 0.0062, z = 1.960
normal interval: +0.33 to +2.77 pp

The standard error (se) is the typical size of the sampling error. A 95% interval reaches 1.96 standard errors to each side of the observed value. Both intervals agree within 0.1 percentage points. The bootstrap needs no formula, so it also works for medians, ratios or model scores. Module 29 covers both methods in depth.

Common mistakes:

  • Using rng.sample() instead of rng.choices(). sample draws without replacement, so a full-size resample is just a shuffle of the same data.
  • Using the global random.choices() without a seed. Each run gives a different interval and nobody can reproduce your report.
  • Too few resamples. With 50 resamples the interval jumps around from seed to seed. 1,000 is a good default for a 95% interval.

Example 8 — Back up the reports with os, shutil and subprocess

Section titled “Example 8 — Back up the reports with os, shutil and subprocess”

Goal: A nightly job copies the monthly reports into a backup folder, zips them and runs a check in a separate Python process. Its settings come from environment variables, as on a server.

os.environ["BACKUP_DIR"] = "output/backup_2024H1" # what the scheduler would set
backup_dir = Path(os.environ.get("BACKUP_DIR", "output/backup"))
archive_format = os.environ.get("BACKUP_FORMAT", "zip")
print(backup_dir.as_posix(), archive_format)
Output
output/backup_2024H1 zip

The first line plays the role of the scheduler, which sets the variable before it starts the script. BACKUP_FORMAT is not set, so the default "zip" is used. Step 3 passes it to make_archive. Remember that every value from os.environ is a string: a number such as "30" needs int().

Step 2 — Copy the folder and verify the copy

Section titled “Step 2 — Copy the folder and verify the copy”
shutil.copytree("data/reports", backup_dir, dirs_exist_ok=True)
pairs = [(src, backup_dir / src.name) for src in paths]
same = all(src.stat().st_size == dst.stat().st_size for src, dst in pairs)
print(len(pairs), "files copied; sizes match:", same)
Output
6 files copied; sizes match: True

paths is the sorted list of report files from Example 3. copytree() copies the whole folder. dirs_exist_ok=True lets the job run again on the next night without an error. Comparing file sizes is a cheap check that every byte arrived.

base_name = "output/reports_2024H1"
archive = shutil.make_archive(base_name, archive_format, root_dir=backup_dir)
print(Path(archive).name, Path(archive).stat().st_size > 0)
Output
reports_2024H1.zip True

make_archive(base_name, format, root_dir) adds the extension (.zip here) to the base name and returns the full path. The code prints only the file name, because the full path differs on every machine.

import json
check_code = """
import csv, json, os, pathlib
folder = pathlib.Path(os.environ["BACKUP_DIR"])
rows = 0
for path in sorted(folder.glob("*.csv")):
with open(path, encoding="utf-8", newline="") as f:
rows += sum(1 for _ in csv.DictReader(f))
print(json.dumps({"files": len(list(folder.glob("*.csv"))), "rows": rows}))
"""
result = subprocess.run(
[sys.executable, "-c", check_code], capture_output=True, text=True, check=True
)
print(json.loads(result.stdout))
Output
{'files': 6, 'rows': 297}

The child inherits BACKUP_DIR from this process’s environment, so the two processes agree on the folder without an argument. The child prints JSON and the parent parses it. JSON is a safe format for a result that crosses a process boundary.

try:
subprocess.run(
[sys.executable, "-c", "import os; open(os.environ['BACKUP_DIR'] + '/x.csv')"],
capture_output=True,
text=True,
check=True,
timeout=60,
)
except subprocess.CalledProcessError as error:
print("check failed with exit code", error.returncode)
print(error.stderr.strip().splitlines()[-1])
Output
check failed with exit code 1
FileNotFoundError: [Errno 2] No such file or directory: 'output/backup_2024H1/x.csv'

The child crashed with a traceback, which Python writes to stderr and ends with exit code 1. check=True turned that into a CalledProcessError in the parent. The last line of the child’s stderr names the problem. A scheduler that sees a non-zero exit code can retry or send an alert.

Common mistakes:

  • Running "python" instead of sys.executable. "python" may be another Python, outside your environment, with other packages.
  • Building the command as one string with shell=True. Pass a list of words.
  • Forgetting check=True. A failed child then returns quietly, and the job reports success.
Mistake Symptom Fix
groupby on unsorted data The same key appears in several groups Sort by the same key first, or use defaultdict(list)
Reusing an iterator from chain, islice or a file The second loop does nothing, with no error Build a new iterator, or store the items in a list
Reading a missing key of a defaultdict Empty entries appear in the result Use d.get(key) or key in d to read
Counter(lines) when you want units Counts of lines, not of units counter[key] += quantity
deque without maxlen as a window The window grows without limit deque(maxlen=n)
A list argument to a cached function TypeError: unhashable type: 'list' Pass a tuple
A cached function that returns a list One caller’s change shows up for all callers Return a tuple or a copy
Naive and aware datetimes mixed TypeError: can't subtract offset-naive and offset-aware datetimes Make every timestamp aware with replace(tzinfo=UTC)
Local times subtracted across DST A 23-hour day reported as 1 day, 0:00:00 Convert both to UTC first
A fixed UTC offset for a city Times one hour wrong for half the year ZoneInfo("America/Chicago")
strptime format does not fit the text ValueError: time data '...' does not match format '...' Check every separator and %d/%m versus %m/%d
A regex without the r prefix \b matches nothing; SyntaxWarning: invalid escape sequence Always write r"..."
re.match where re.search was meant None for a pattern in the middle of the line search looks anywhere; match only at the start
Greedy .* One match swallows several fields .*? or a precise class such as \S+
stdev versus pstdev mixed up A slightly different standard deviation from pandas stdev (n − 1) matches pandas .std()
The global random functions Results change on every run rng = random.Random(42)
subprocess.run without check=True A failed child goes unnoticed check=True, or test returncode
"python" as the child command The child misses your packages sys.executable
  • Web development: frameworks route URLs with regular expressions, validate form fields with fullmatch, cache settings with lru_cache and store every timestamp in UTC, converting to the user’s time zone only in the page.
  • Automation: backup and deploy scripts read their settings from environment variables, copy and zip folders with shutil, and run tools such as git with subprocess.run([...], check=True).
  • Operations and monitoring: log analyzers count status codes with Counter, alert on a rolling window with deque and group events with defaultdict.
  • Tooling: test runners send work to other processes in batches, and command-line tools build all option combinations with itertools.product to test them.
  • Counter counts, defaultdict groups, deque(maxlen=n) keeps a rolling window and namedtuple gives tuple fields their names.
  • itertools tools are lazy and work on any iterable: chain joins, islice slices, batched chunks, accumulate gives running totals, pairwise gives neighbors, groupby groups consecutive keys, product and combinations build grids and pairs.
  • An iterator is used up after one pass. Build a new one for a second pass.
  • partial fixes arguments, reduce folds a sequence and cache/lru_cache memoize pure functions. cache_info() shows the hits and misses.
  • Parse dates with fromisoformat or strptime, format them with isoformat or strftime, and compute with timedelta.
  • Make timestamps aware, store and compute them in UTC, and convert with ZoneInfo only for display.
  • Write regex patterns as raw strings. Use named groups, compile patterns you reuse, and use re.VERBOSE to comment long patterns.
  • math, statistics and a seeded random.Random(42) cover quick numeric work and reproducible sampling.
  • os.environ holds settings, shutil copies and archives files, and subprocess.run([sys.executable, ...], check=True) runs another program safely.

Q1. What does Counter("banana")["n"] return, and what does Counter("banana")["z"] return?

Answer

2 and 0. A Counter counts each character of the string. A missing key gives 0, not a KeyError.

Q2. After d = defaultdict(list) and print(len(d["S9"])), is "S9" in d true or false? Why?

Answer

True. Reading a missing key calls the default factory list(), which creates d["S9"] = []. Use d.get("S9") to read without creating the key.

Q3. Why is deque(maxlen=6) better than a list for a rolling window over a long stream of readings?

Answer

The deque drops the oldest value by itself when it is full, and adding or removing at either end takes constant time. A list needs a manual pop(0), which moves every remaining item each time.

Q4. groupby(["ok", "warn", "ok"]) gives how many groups? What must you do to get one group per status?

Answer

Three groups: ok, warn, ok. groupby groups only consecutive equal items. Sort the data by the same key first, or count with Counter.

Q5. You run rows = chain(a, b), then print(len(list(rows))) twice. The first print shows 10. What does the second show, and why?

Answer

0. chain returns an iterator, and the first list() used it up. Build a new chain(a, b) for a second pass.

Q6. Which two conditions must a function meet before you put @cache on it?

Answer

It must be pure (the same arguments always give the same result, with no side effects that you need every time), and its arguments must be hashable. Also clear the cache when the data behind it changes.

Q7. A job is scheduled at 06:00 in America/Chicago every day. Should you add timedelta(days=1) to the aware local time or to the UTC time? What is the difference across a DST change?

Answer

Add it to the aware local time. Python keeps the wall-clock time, so the job stays at 06:00 local time, and its UTC time moves by one hour. Adding a day in UTC keeps exactly 24 hours, so the local time would move to 05:00 or 07:00.

Q8. Why should a regex pattern be a raw string? Give an example where it matters.

Answer

In a normal string Python reads backslash codes before re sees the pattern. "\b" becomes a backspace character, so re.search("\bERROR\b", line) never matches a word. r"\bERROR\b" passes the backslashes to re unchanged.

Q9. What is the difference between re.match, re.search and re.fullmatch?

Answer

match matches only at the start of the text. search finds the first match anywhere. fullmatch matches only when the whole text fits the pattern, which makes it the tool for validating a value such as a product id.

Q10. What does re.findall(r"(\d{3}) (\d+)ms", text) return: whole matches or something else?

Answer

A list of tuples, one per match, with the two groups as strings, for example [('201', '93')]. With groups in the pattern, findall returns the groups, not the whole match.

Q11. Why use rng = random.Random(42) instead of random.seed(42) and the module-level functions?

Answer

The module-level functions share one hidden generator with every other part of the program. Any library that draws from it changes your sequence. A dedicated instance is yours alone, so your results stay reproducible.

Q12. Why pass [sys.executable, "-c", code] to subprocess.run instead of the string "python -c ..." with shell=True?

Answer

sys.executable is the Python that runs your script, so the child sees the same environment and packages. A list goes to the program directly, with no shell, so there are no quoting problems and no risk of shell injection.

Your progress

0 / 4 done

  • Exercises: 28 exercises on collections, itertools, functools, datetime, re, statistics, random and automation, with hints and full solutions.
  • Mini-project: build an operations report from the application log.
  • Cheat sheet: every tool of this module, a “which tool for which job” table, regex syntax and date format codes on one page.
  • Part 1 checkpoint: mixed exercises across modules 01–09 and a self-assessment rubric.
  • Next module: 10. Iterators and generators explains how iterators work inside and builds lazy pipelines with generators and itertools recipes.