Skip to content
  • Standard Library Tour · Python

Standard Library Tour

LearnViaNotes @learnvianotes· 4 min read

“Batteries included”: before installing a package, check the standard library. A map of the modules worth knowing, with a tiny example of each.

Where things live

NeedModule(s)Covered in
Containers & algorithmscollections, heapq, bisect, arrayData Structures
Iteration & functionsitertools, functools, operatorAdvanced Python, Functions
Textstring, re, textwrap, difflib, unicodedataStrings & Numbers
Numbersmath, decimal, fractions, statistics, randomNumbers, below
Files & formatspathlib, shutil, json, csv, tomllib, pickle, sqlite3, zipfileErrors, Modules & Files
Datesdatetime, zoneinfo, time, calendarDates & Times
OS & processesos, sys, subprocess, argparse, loggingthis group
Concurrencythreading, multiprocessing, concurrent.futures, asyncio, queueConcurrency
Testing & debuggingunittest, doctest, pdb, timeit, cProfile, tracemallocTesting & Tooling
Security & idshashlib, hmac, secrets, uuid, base64below
Internet (no network needed to parse)urllib.parse, http, email, html, ipaddressbelow

random & statistics

Python
import random, statistics

random.seed(42)                         # same seed → same sequence (reproducible experiments)
first = [random.randint(1, 6) for _ in range(5)]
random.seed(42)
print(first == [random.randint(1, 6) for _ in range(5)])   # True

rng = random.Random(7)                  # an independent generator with its own state
deck = list("AKQJ")
rng.shuffle(deck)                       # in place
print(len(rng.sample(range(100), 3)), rng.choice(deck) in deck)   # 3 True

data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(data), statistics.median(data), statistics.mode(data))   # 5 4.5 4
print(statistics.pstdev(data), round(statistics.stdev(data), 3))             # 2.0 2.138

secrets, hashlib, uuid, base64

Python
import secrets, hashlib, hmac, uuid, base64

token = secrets.token_urlsafe(16)                  # unpredictable, URL-safe
print(len(token) >= 16)                            # True
print(secrets.compare_digest("abc", "abc"))        # True   ← constant-time comparison

print(hashlib.sha256(b"hello").hexdigest()[:16])   # 2cf24dba5fb0a30e
sig = hmac.new(b"secret-key", b"payload", hashlib.sha256).hexdigest()
print(len(sig))                                    # 64

u = uuid.uuid4()                                   # random unique id
print(u.version, len(str(u)))                      # 4 36

encoded = base64.b64encode(b"hi there")
print(encoded, base64.b64decode(encoded))          # b'aGkgdGhlcmU=' b'hi there'

Text helpers: string, textwrap, difflib, pprint

Python
import string, textwrap, difflib, pprint

print(string.ascii_lowercase[:5], string.digits, string.punctuation[:4])   # abcde 0123456789 !"#$
print(textwrap.shorten("The quick brown fox jumps over the lazy dog", width=25))   # The quick brown fox [...]
print(textwrap.wrap("one two three four five", width=9))   # ['one two', 'three', 'four five']
print(difflib.get_close_matches("pyhton", ["python", "java", "ruby"]))   # ['python']
print(round(difflib.SequenceMatcher(None, "kitten", "sitting").ratio(), 2))   # 0.62
print(pprint.pformat({"b": [1, 2], "a": {"x": 1}}))        # {'a': {'x': 1}, 'b': [1, 2]}   ← keys sorted

urllib.parse, ipaddress, html

Python
from urllib.parse import urlparse, parse_qs, urlencode, quote
import ipaddress, html

u = urlparse("https://shop.example.com:8443/search?q=red+shoes&page=2#top")
print(u.scheme, u.hostname, u.port, u.path)        # https shop.example.com 8443 /search
print(parse_qs(u.query))                           # {'q': ['red shoes'], 'page': ['2']}
print(urlencode({"q": "café & co", "n": 3}))       # q=caf%C3%A9+%26+co&n=3
print(quote("a b/c"))                              # a%20b/c

net = ipaddress.ip_network("10.0.0.0/30")
print([str(h) for h in net.hosts()])               # ['10.0.0.1', '10.0.0.2']
print(ipaddress.ip_address("192.168.1.5").is_private)   # True
print(html.escape("<b>Tom & Jerry</b>"))           # &lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

Compression & archives in memory

Python
import gzip, io, zipfile

raw = b"python " * 1000
packed = gzip.compress(raw)
print(len(raw), len(packed) < 100, gzip.decompress(packed) == raw)   # 7000 True True

buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    zf.writestr("notes/a.txt", "alpha")
    zf.writestr("notes/b.txt", "beta")
with zipfile.ZipFile(buf) as zf:
    print(zf.namelist(), zf.read("notes/b.txt"))   # ['notes/a.txt', 'notes/b.txt'] b'beta'

weakref, contextvars, dis

Python
import weakref, dis

class Big:
    pass

obj = Big()
ref = weakref.ref(obj)             # doesn't keep obj alive
print(ref() is obj)                # True
del obj
print(ref())                       # None   ← freed as soon as the last strong reference went

cache = weakref.WeakValueDictionary()   # entries vanish when values are garbage-collected

def add(a, b):
    return a + b
ops = [i.opname for i in dis.get_instructions(add)]
print("BINARY_OP" in ops)          # True   ← dis shows the bytecode CPython runs
Handy `python -m` one-liners
$ python -m http.server 8000        # static file server
$ python -m json.tool data.json     # pretty-print / validate JSON
$ python -m timeit "sum(range(1000))"
$ python -m venv .venv              # create a virtual environment
$ python -m zipfile -l bundle.zip   # list an archive
$ python -m calendar 2026 9         # print a month calendar

When should you reach for a third-party package instead of the standard library?

random vs secrets?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report