Lesson 37 of 52Python power tools
Standard Library Tour
The stdlib tools interviewers expect, from Counter and heapq to bisect, plus a map of logging, uuid, decimal, subprocess and more.
Python ships "batteries included": a standard library of hundreds of modules, already installed everywhere Python is. In a coding interview, reaching for Counter, deque or heapq turns a 20-line answer into 3 lines and shows you know the language. In real work, it saves you from installing a package for something the stdlib already does well. This lesson is the short list worth knowing cold, followed by a map of the rest that points you to the lessons covering each area in depth.
collections: better containers
Counter: count things
A Counter is a dict that counts. Give it any iterable and it tallies how many times each item appears. Missing keys read as 0 instead of raising KeyError.
Press Run (⌘ Enter) to see what happens.defaultdict: dicts that create missing values
defaultdict(list) calls list() to create a value the first time you touch a missing key. It is perfect for grouping.
Press Run (⌘ Enter) to see what happens.list.pop(0) is O(n) because every other element shifts left. deque.popleft() is O(1). That is why BFS always uses a deque as its queue. Regular dicts keep insertion order since Python 3.7, so you only need OrderedDict for its extra methods, move_to_end and popitem(last=False).
deque instead of list?heapq: always grab the smallest
A heap is a list arranged so that the smallest item is always at index 0. Pushing and popping take O(log n). Python's heaps are min-heaps; for a max-heap, push negated values.
Press Run (⌘ Enter) to see what happens.Use a heap for "top k", "k-th largest", merging sorted lists, task schedulers and Dijkstra's shortest path.
bisect: binary search on sorted lists
bisect finds where a value belongs in a sorted list in O(log n), and insort inserts it there, keeping the list sorted.
Search the whole sorted list for the first spot where 75 could go.
Press Run (⌘ Enter) to see what happens.The rest of the map
The sections above are the interview core. The standard library has much more, and several areas now have a lesson of their own. Treat this part of the tour as a map: a paragraph on what each area is for, what to remember, and where the full story lives.
itertools, functools and operator
itertools gives you lazy building blocks for loops: chain, islice, groupby, product, combinations, pairwise, batched, accumulate. functools gives you tools for functions themselves: cache, lru_cache, partial, reduce, wraps, singledispatch. A taste:
Press Run (⌘ Enter) to see what happens.The two traps that bite at work: groupby only groups consecutive equal keys, so sort first, and lru_cache on a method keeps every self alive. functools, itertools and operator covers both, plus caching in depth and singledispatch.
math and random
Press Run (⌘ Enter) to see what happens.Compare floats with math.isclose, never ==. random is for simulations, sampling and tests; it is predictable by design, so never use it for tokens or passwords (see secrets below).
datetime and zoneinfo
datetime handles dates, times and durations; zoneinfo (3.9+) gives you real time zones from the IANA database. The rule that prevents most bugs: store timezone-aware UTC values and convert to local time only for display. Use datetime.now(datetime.UTC), not the deprecated utcnow(). timedelta does real calendar arithmetic:
What does this print?
from datetime import date, timedelta d = date(2026, 1, 31) + timedelta(days=1) print(d.month, d.day)
Daylight saving gaps and folds, parsing, Unix timestamps and testing code that reads the clock are all in Dates, Times and Time Zones.
re
Regular expressions find, validate and rewrite text patterns. Write patterns as raw strings (r"\d+"), use re.fullmatch for validation and re.search to find a match anywhere, and remember that re.findall returns the groups, not the whole match, when the pattern has groups. Prefer plain string methods (startswith, split, in) when they are enough. Regular Expressions covers the syntax, flags, verbose patterns and catastrophic backtracking.
enum and dataclasses
Enum names a fixed set of options so a typo becomes an error instead of a silent bug; StrEnum (3.11) members are also real strings, convenient for JSON and databases. Flag packs several options into one value. The Enums lesson covers all of these plus exhaustive match handling, and you met dataclasses in the Dataclasses lesson.
Files, processes and the command line
These four modules turn a Python file into a tool other people can run.
pathlib: paths as objects.Path("data") / "2026" / "report.csv"builds paths that work on every OS, and.name,.stem,.suffix,.parent,.exists(),.read_text()and.glob("*.csv")replace most ofos.path.argparse: real command-line options with--help, types, choices and error messages for free.subprocess: run other programs. Usesubprocess.run([...], check=True, capture_output=True, text=True)with a list of arguments;shell=Truewith user input is a command injection hole.shlex: split and quote shell-style strings safely, for when you must build or parse a command line.
Press Run (⌘ Enter) to see what happens.The example uses PurePosixPath so it prints the same everywhere; in real code you use Path, which also touches the file system. Passing a list to parse_args is also how you test an argparse CLI without a terminal. subprocess cannot run in the browser, so here is the shape to copy:
import subprocess
result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
check=True, # raise CalledProcessError on a non-zero exit
capture_output=True,
text=True, # str instead of bytes
timeout=10,
)
print(result.stdout.strip())Scripting and Automation goes deeper on all four, including stdout versus stderr, exit codes, shutil, tempfile and clean shutdown. Files and JSON covers pathlib for reading and writing.
logging
print is for output; logging is for diagnostics. Each module asks for a named logger, the entry point configures handlers once, and levels (DEBUG, INFO, WARNING, ERROR) decide what is shown without editing code.
Press Run (⌘ Enter) to see what happens.Two habits from that block: pass values as arguments ("order %s", order_id) rather than f-strings, so formatting is skipped for messages nobody sees, and use log.exception inside except so the traceback is recorded. The logging Module covers handlers, request ids, structured logs and the bugs everyone hits.
IDs and secrets: uuid and secrets
uuid makes globally unique ids. uuid4() is fully random. uuid7() (3.14) starts with a timestamp, so ids created later sort later. That matters for databases: random uuid4 primary keys scatter inserts across a B-tree index, while time-ordered uuid7 keys append near the end, which keeps indexes smaller and inserts faster. secrets is the module for anything an attacker must not guess: session tokens, password reset links, API keys. It reads from the operating system's secure random source.
Press Run (⌘ Enter) to see what happens.secrets.compare_digest compares in constant time, so an attacker cannot learn a token one character at a time from response timings. A uuid7 leaks its creation time, so do not use it where that is sensitive, and no UUID is a substitute for a secret token. Python Security Pitfalls covers tokens and password hashing.
Exact numbers and quick stats: decimal, fractions, statistics
Floats are binary, so 0.1 cannot be stored exactly. For money, use decimal.Decimal, built from strings, and round explicitly with quantize and a named rounding mode. fractions.Fraction keeps exact ratios. statistics gives you mean, median, standard deviation and quantiles without installing anything.
Press Run (⌘ Enter) to see what happens.Notice two things. round(2.675, 2) gives 2.67 because the float is really 2.67499..., and Python's round uses banker's rounding anyway; Decimal with ROUND_HALF_UP gives the 2.68 an accountant expects. And one slow request (240 ms) drags the mean to about 42 while the median stays at 13.5. That is why latency dashboards show the median and high percentiles, not the average. Many teams also store money as integer pence or cents, which is fine too; the bug is mixing floats into it.
What does this print?
from decimal import Decimal
print(Decimal("1.10") + Decimal("2.20"), Decimal(1.1) == Decimal("1.1"))Text helpers: textwrap, pprint, difflib
Small modules that save you writing fiddly code by hand:
textwrap:dedentstrips the common indentation from a triple-quoted string (help text, SQL, test fixtures),fillwraps to a width,shortentruncates on a word boundary.pprint: prints nested dicts and lists readably.pprint.ppkeeps dict order.difflib:get_close_matchespowers "did you mean...?" suggestions, andunified_diffproduces the same format asgit diff, which is handy in tests and config tools.
Press Run (⌘ Enter) to see what happens.What to reach for when
| You need to... | Reach for |
|---|---|
| Count occurrences, find the most common | collections.Counter |
| Group items into lists by key | collections.defaultdict(list) |
| A queue, BFS, or a sliding window of recent items | collections.deque (with maxlen) |
| An LRU cache by hand | collections.OrderedDict |
| Top k, k-th largest, a priority queue | heapq |
| Search or insert in a sorted list | bisect |
| Combinations, permutations, chunks, running totals | itertools |
| Memoise a function, adapt arguments | functools.cache, partial |
| Float comparison, combinatorics, gcd | math |
| Dates, durations, parsing and formatting times | datetime |
| Find or validate patterns in text | re |
| A fixed set of named options | enum |
| A data record class | dataclasses |
| Secure random tokens | secrets |
| Build and inspect file paths | pathlib (see Files and JSON) |
| Command-line options for a script | argparse (see Scripting and Automation) |
| Run another program | subprocess.run([...], check=True) |
Diagnostics with levels, not print | logging (see The logging Module) |
| Unique ids that sort by creation time | uuid.uuid7() (3.14+) |
| Money and exact decimal rounding | decimal.Decimal from strings |
| Mean, median, percentiles | statistics |
| Strip indentation, wrap or shorten text | textwrap |
| "Did you mean...?" suggestions, text diffs | difflib |
Match each interview problem to the stdlib tool that cracks it.
Counter("mississippi").most_common(1) return?LRU cache with OrderedDict
Implement a least recently used (LRU) cache with a fixed capacity, using collections.OrderedDict.
LRUCache(capacity)creates an empty cache.get(key)returns the value, or-1if the key is missing. A successfulgetmarks the key as most recently used.put(key, value)inserts or updates the key and marks it most recently used. If that makes the cache bigger thancapacity, evict the least recently used key.len(cache)returns how many keys are stored.
Both operations should be O(1).
c = LRUCache(2)
c.put("a", 1); c.put("b", 2)
c.get("a") # 1 ("a" is now most recent)
c.put("c", 3) # evicts "b", the least recently used
c.get("b") # -1Top k frequent words
Given a list of words and an integer k, return the k most frequent words, most frequent first. When two words have the same count, the one that comes first alphabetically wins.
top_k_words(["go", "py", "go", "js", "py", "go"], 2) # ["go", "py"]
top_k_words(["b", "a", "c", "a", "b", "c"], 2) # ["a", "b"] (all tie, alphabetical)If k is larger than the number of distinct words, return them all. Use the standard library: Counter plus either sorted with a good key or heapq.nsmallest.
- Counter
- A dict subclass that counts hashable items; missing keys read as 0; has
most_common(k). - defaultdict
- A dict that calls a factory (like
list) to create values for missing keys. - deque
- A double-ended queue with O(1) appends and pops at both ends; optional
maxlen. - heapq
- Functions that keep a list as a min-heap: O(log n) push and pop of the smallest item.
- bisect
- Binary search helpers to find insertion points in, and insert into, sorted lists.
- Enum
- A class of named constant members;
StrEnummembers are also strings. - uuid7
- A time-ordered UUID (3.14+). Sorts by creation time, which suits database indexes better than random
uuid4. - Decimal
- An exact decimal number type for money. Build it from strings and round with
quantize. - secrets
- The module for unguessable tokens, using the operating system's secure random source.