Python cheat sheet
Live-coding tasks in Python rarely need a library. They need dict, set, sorted, Decimal, datetime and a few modules from the standard library, typed quickly and without mistakes. The first block is what to have in your fingers; the rest is for looking up and for the questions that come after the code works.
In your fingers
Section titled “In your fingers”from collections import defaultdict, Counter, deque, OrderedDictfrom datetime import datetime, date, timedelta, time, timezonefrom decimal import Decimal, ROUND_HALF_UP, ROUND_DOWNfrom dataclasses import dataclass, fieldimport heapq, bisect, calendar, functools, itertools, re
d = defaultdict(list); d[key].append(x)c = Counter(items); c.most_common(3)q = deque(maxlen=100); q.append(x); q.popleft()od = OrderedDict(); od.move_to_end(k); od.popitem(last=False) # LRU: drop the oldest
sorted(rows, key=lambda r: (r["date"], r["id"])) # several keyssorted(rows, key=lambda r: (-r["amount"], r["id"])) # amount descending, then idmin(cands, key=lambda c: (abs(c.diff), c.id)) # the best one, with a tie-breakerheapq.nsmallest(5, rows, key=...) # top N without a full sortbisect.bisect_left(sorted_list, x) # search in a sorted list
for a, b in zip(xs, xs[1:]): ... # neighbouring pairsfor i, x in enumerate(xs, 1): ... # numbered from 1itertools.groupby(sorted_rows, key=...) # only on sorted input!What to use when
Section titled “What to use when”- Group and sum →
defaultdict(Decimal); a list per key →defaultdict(list). - Count things →
Counter. - “Have I seen it?”, duplicates → a
setcalledseen. - The latest record per key → a
dict, overwritten only when the new record is newer. - Top k →
heapq.nsmallest(k, rows, key=lambda r: (-r.amount, r.id)). - A sliding time window, a rate limit → a
deque, old items dropped from the left. - Search in a sorted list →
bisect. - Overlapping periods → sort by start, then one pass.
- Allocate an amount to debts → one loop:
pay = min(left, due),if pay > 0,breakwhenleft == 0. - Data from a database → filter and
GROUP BYin SQL; bring only a small result into Python.
The order of work for any function: a small input and output by hand, the rule in one sentence, the edge cases as a comment, the code, a print of the example, then the edge cases.
datetime(2026, 9, 30) + timedelta(days=30) # 2026-10-30 00:00:00calendar.monthrange(2026, 2)[1] # 28: days in the monthdt.replace(day=1) # start of the month(d2 - d1).days # difference in daysdatetime.combine(d, time()) # midnight of a datedatetime.fromisoformat("2026-09-30 10:00:00") # parse an ISO stringYou cannot add months with timedelta. Compute the year and the month with // and %, and cap the day with calendar.monthrange: 31 January plus one month is 28 February 2026. A datetime with a time zone (aware) and one without (naive) cannot be compared: Python raises TypeError.
Decimal("0.1") + Decimal("0.2") == Decimal("0.3") # True; with float it is Falseamount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) # 0.125 -> 0.13amount.quantize(Decimal("0.01"), rounding=ROUND_DOWN) # down: 23.9976 -> 23.99round(amount, 2) # still a Decimal, but banker's: 0.125 -> 0.12Decimal(str(0.1)) # from a float, only through strDecimal(0.1) without str keeps the binary error of the float: 0.1000000000000000055511151231257827021181583404541015625.
A decorator
Section titled “A decorator”A decorator with a parameter has three levels: the factory takes the parameter, the decorator takes the function, the wrapper takes the call.
import functools
def retry(times: int): """Call the function again after a ConnectionError, at most `times` attempts in total.""" def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return func(*args, **kwargs) except ConnectionError: if attempt == times: raise return wrapper return decorator
@retry(times=3)def fetch_payout(payout_id: str) -> str: """Ask the marketplace API for one payout.""" ...Thanks to functools.wraps, fetch_payout.__name__ is still "fetch_payout" and the docstring survives. Without it, both belong to wrapper.
Complexity to name
Section titled “Complexity to name”dictandsetlookup:O(1)on average.x in list:O(n). Sorting:O(n log n). A heap push or pop:O(log n).- Two nested loops over n items are
O(n²): on 100,000 rows that is already slow. - Top k with a heap:
O(n log k)time andO(k)memory. - Sweep line: turn periods into +1 and −1 events, sort them, then one pass.
O(n log n).
Traps interviewers ask about
Section titled “Traps interviewers ask about”- A mutable default argument (
def f(x, seen=set()),_cache={}) lives between calls. Default toNoneand create the object inside. - Money in
float:0.1 + 0.2 != 0.3. UseDecimalfrom strings.round()on aDecimalis banker’s rounding; for half-up or down, usequantize. - Division:
int / intgives afloat,Decimal / Decimalgives aDecimal(divide money this way).//on anintrounds down (-7 // 2 == -4), on aDecimaltowards zero (Decimal(-7) // 2 == -3). x in listisO(n), so inside a loop it isO(n²). Use asetor adict.- Changing a
dictwhile you loop over it raisesRuntimeError: dictionary changed size during iteration; alistsilently skips items. Loop over a copy:for k in list(d). defaultdictcreates a key on read:d["missing"]adds it. Returndict(d), and test withk in dord.get(k).sortedis stable: items with equal keys keep their order. For “amount descending, then id”, use the tuple key(-amount, id).isor==:ischecks that it is the same object,==compares values. Useisonly forNone.- “What if many threads call it?” (a cache, a rate limiter) → a
threading.Lockaround read–change–write. Between processes or servers → Redis, or a unique key in the database.
The database from Python
Section titled “The database from Python”# sqlite3, DuckDB and the Python tasks on this site: ? placeholdersrows = con.execute( "SELECT product_id, start_time FROM transactions WHERE product_id = ? AND start_time >= ?", [product_id, since],).fetchall()
# SQLAlchemy, common in online interview editors: :name placeholdersrows = conn.execute( sa.text("SELECT product_id, start_time FROM transactions WHERE product_id = :product"), {"product": product_id},).mappings().all()Pass values only as parameters, never with an f-string: that is SQL injection, and parameters also handle types and quotes. Do the heavy work (filters, GROUP BY) in SQL, and bring a small result into Python.
pytest
Section titled “pytest”pytest -k merge # only the tests whose name contains "merge"pytest -x # stop at the first failurepytest -k merge -vv # verbose: every test and the full diffLooking things up without AI
Section titled “Looking things up without AI”The fastest help is in the editor itself. It works in most interview editors and is not AI:
help(heapq.nsmallest) # signature and description: "Equivalent to: sorted(iterable, key=key)[:n]"dir(itertools) # what the module has: accumulate, groupby, pairwise, …print(Decimal.quantize.__doc__) # the docstring of one methodThe documentation is usually allowed in the interview:
- A module page is
docs.python.org/3/library/<module>.html:heapq,itertools,collections,datetime,decimal,bisect,functools. Search the page for the function name; the end of the page often has examples and recipes. - The Sorting HOWTO covers
key, several keys and stability. - The
decimalpage has a FAQ: search forquantizeor “two decimal places”. - The
datetimepage has a table of format codes forstrftime()andstrptime().
Further reading
Section titled “Further reading”- Python: collections —
defaultdict,Counter,deque,OrderedDict. - Python: Sorting HOWTO — key functions, several keys, stability.
- Python: decimal —
quantize, rounding modes and the FAQ. - Python: datetime — aware and naive objects,
fromisoformat, format codes. - Python: heapq and functools.wraps.
Related topics
Section titled “Related topics”- Recipes for a sheet of paper — the Python recipes, one line each.
- dict and Counter — grouping and counting, with drills.
- Money and Decimal — rounding, splitting and allocating money.
- Testing and complexity — what to say once the code works.
- Python and SQL — parameters and where the work should happen.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.