Skip to content

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.

24 min read0/6 questions

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.

Python
from collections import Counter votes = Counter(["py", "js", "py", "go", "py", "js"])print(votes)print(votes["py"], votes["rust"]) # missing key -> 0print(votes.most_common(2))votes.update(["go", "go"])print(votes["go"])print(Counter("listen") == Counter("silent")) # anagram check
Output
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.

Python
from collections import defaultdict, deque, OrderedDict by_team = defaultdict(list)for name, team in [("Ada", "api"), ("Sam", "web"), ("Leo", "api")]: by_team[team].append(name) # no "if team not in" neededprint(dict(by_team)) # deque: fast appends and pops at BOTH endsq = deque([1, 2, 3])q.appendleft(0)q.append(4)print(q.popleft(), q.pop(), q)recent = deque(maxlen=3) # keeps only the last 3for page in ["home", "docs", "blog", "about"]: recent.append(page)print(list(recent)) # OrderedDict: a dict with move_to_end, handy for LRU cachesod = OrderedDict(a=1, b=2, c=3)od.move_to_end("a")print(list(od), od.popitem(last=False))
Output
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).

Quick check
You process a queue of a million jobs, always taking from the front. Why use deque instead of list?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import heapq tasks = []heapq.heappush(tasks, (3, "write docs"))heapq.heappush(tasks, (1, "fix prod bug"))heapq.heappush(tasks, (2, "review PR"))while tasks: priority, task = heapq.heappop(tasks) # tuples compare by first item print(priority, task) scores = [42, 7, 99, 13, 58, 81]print(heapq.nlargest(3, scores), heapq.nsmallest(2, scores)) nums = [5, 1, 8, 3]heapq.heapify(nums) # O(n), in placeprint(nums[0])
Output
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.

bisect_left(grades, 75)
50
0
↑lo
60
1
70
2
80
3
90
4

Search the whole sorted list for the first spot where 75 could go.

1/5
Python
import bisect def letter(score): cutoffs = [60, 70, 80, 90] return "FDCBA"[bisect.bisect_right(cutoffs, score)] print([letter(s) for s in [55, 60, 79, 80, 99]]) sorted_ids = [3, 8, 15]bisect.insort(sorted_ids, 10)print(sorted_ids)
Output
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:

Python
from functools import reduce, partialfrom itertools import accumulateimport operator print(reduce(operator.mul, [1, 2, 3, 4])) # fold a list into one valueprint(list(accumulate([3, 1, 4, 1, 5]))) # running totals (prefix sums) base2 = partial(int, base=2) # pre-fill some argumentsprint(base2("1010"), base2("1111"))
Output
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

Python
import math, random print(math.sqrt(16), math.ceil(4.1), math.floor(-4.1), math.inf > 10**100)print(math.gcd(12, 18), math.comb(5, 2), math.isclose(0.1 + 0.2, 0.3)) random.seed(42) # reproducible "random" for testsprint(random.randint(1, 6), random.choice(["a", "b", "c"]))deck = list(range(5)); random.shuffle(deck); print(deck)
Output
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:

Predict the outputPython

What does this print?

from datetime import date, timedelta
d = date(2026, 1, 31) + timedelta(days=1)
print(d.month, d.day)
Need a nudge? Hints walk you through it.

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 of os.path.
  • argparse: real command-line options with --help, types, choices and error messages for free.
  • subprocess: run other programs. Use subprocess.run([...], check=True, capture_output=True, text=True) with a list of arguments; shell=True with 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.
Python
import argparse, shlexfrom pathlib import PurePosixPath p = PurePosixPath("/srv/app/reports/2026-10/summary.final.csv")print(p.name, p.stem, p.suffix, p.parent.name)print(p.with_suffix(".json"))print(PurePosixPath("/srv/app") / "logs" / "api.log") parser = argparse.ArgumentParser(prog="export")parser.add_argument("month")parser.add_argument("--format", choices=["csv", "json"], default="csv")parser.add_argument("--dry-run", action="store_true")args = parser.parse_args(["2026-10", "--dry-run"])print(args.month, args.format, args.dry_run) line = 'grep -i "disk full" /var/log/app.log'print(shlex.split(line))print(shlex.join(["cp", "my report.pdf", "/tmp"]))
Output
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:

deploy.py
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.

Python
import logging, sys logging.basicConfig( stream=sys.stdout, level=logging.INFO, format="%(levelname)s %(name)s: %(message)s",)log = logging.getLogger("billing") log.debug("not shown: below INFO")log.info("charged order %s for %d pence", "A-17", 1299)try: 1 / 0except ZeroDivisionError: log.exception("refund failed")
Output
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.

Python
import secrets, uuid a, b = uuid.uuid7(), uuid.uuid7()print(a.version, a < b) # time-ordered: later ids sort laterprint(uuid.uuid4().version) # fully random print(len(secrets.token_urlsafe(32)) >= 32)print(secrets.compare_digest("s3cret", "s3cret"))print(secrets.choice(["red", "green", "blue"]) in {"red", "green", "blue"})
Output
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.

Python
from decimal import Decimal, ROUND_HALF_UPfrom fractions import Fractionimport statistics print(0.1 + 0.2 == 0.3, Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))print(Decimal(0.1)) # built from a float: too lateprice = Decimal("19.99") * 3 * Decimal("1.2") # add 20% taxprint(price, price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))print(round(2.675, 2), Decimal("2.675").quantize(Decimal("0.01"), ROUND_HALF_UP)) print(Fraction(1, 3) + Fraction(1, 6), Fraction(1, 3) * 3) latency_ms = [12, 15, 11, 240, 14, 13, 16, 12]print(statistics.mean(latency_ms), statistics.median(latency_ms))print(round(statistics.stdev(latency_ms), 1))print(statistics.quantiles(latency_ms, n=4))
Output
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.

Predict the outputPython

What does this print?

from decimal import Decimal
print(Decimal("1.10") + Decimal("2.20"), Decimal(1.1) == Decimal("1.1"))
Need a nudge? Hints walk you through it.

Text helpers: textwrap, pprint, difflib

Small modules that save you writing fiddly code by hand:

  • textwrap: dedent strips the common indentation from a triple-quoted string (help text, SQL, test fixtures), fill wraps to a width, shorten truncates on a word boundary.
  • pprint: prints nested dicts and lists readably. pprint.pp keeps dict order.
  • difflib: get_close_matches powers "did you mean...?" suggestions, and unified_diff produces the same format as git diff, which is handy in tests and config tools.
Python
import difflib, pprint, textwrap def help_text(): return textwrap.dedent("""\ Usage: export MONTH --format csv or json """)print(help_text())print(textwrap.shorten("The nightly export failed because the disk was full", width=30))print(textwrap.fill("Wrap long log lines or emails to a fixed width for terminals.", width=28)) config = {"db": {"host": "db.internal", "port": 5432, "pool": {"min": 2, "max": 20}}, "features": ["search", "export", "billing"]}pprint.pp(config, width=50) commands = ["deploy", "rollback", "status", "logs"]print(difflib.get_close_matches("statsu", commands)) old = ["host = db1", "port = 5432", "debug = false"]new = ["host = db2", "port = 5432", "debug = false"]print("\n".join(difflib.unified_diff(old, new, "before", "after", lineterm="")))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
You are generating password reset links. Which call should produce the token?
Need a nudge? A hint rules out a wrong answer.

What to reach for when

You need to...Reach for
Count occurrences, find the most commoncollections.Counter
Group items into lists by keycollections.defaultdict(list)
A queue, BFS, or a sliding window of recent itemscollections.deque (with maxlen)
An LRU cache by handcollections.OrderedDict
Top k, k-th largest, a priority queueheapq
Search or insert in a sorted listbisect
Combinations, permutations, chunks, running totalsitertools
Memoise a function, adapt argumentsfunctools.cache, partial
Float comparison, combinatorics, gcdmath
Dates, durations, parsing and formatting timesdatetime
Find or validate patterns in textre
A fixed set of named optionsenum
A data record classdataclasses
Secure random tokenssecrets
Build and inspect file pathspathlib (see Files and JSON)
Command-line options for a scriptargparse (see Scripting and Automation)
Run another programsubprocess.run([...], check=True)
Diagnostics with levels, not printlogging (see The logging Module)
Unique ids that sort by creation timeuuid.uuid7() (3.14+)
Money and exact decimal roundingdecimal.Decimal from strings
Mean, median, percentilesstatistics
Strip indentation, wrap or shorten texttextwrap
"Did you mean...?" suggestions, text diffsdifflib
Match the pairs0/5 matched

Match each interview problem to the stdlib tool that cracks it.

Choose an item, then its match on the other side.
Quick check
What does Counter("mississippi").most_common(1) return?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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 -1 if the key is missing. A successful get marks 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 than capacity, 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")       # -1
Python
from collections import OrderedDict class LRUCache: def __init__(self, capacity: int) -> None: pass def get(self, key): pass def put(self, key, value) -> None: pass def __len__(self) -> int: pass
ChallengeMedium

Top 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.

Python
from collections import Counterimport heapq def top_k_words(words: list[str], k: int) -> list[str]: pass
Key terms
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; StrEnum members 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.