Skip to content

13. Pythonic code — Cheat sheet

The essentials of module 13 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
loop over items the items directly for temp in temps:
loop with a counter enumerate(it, start=1) for n, row in enumerate(rows, start=2):
loop over two columns together zip(a, b, strict=True) for sid, t in zip(ids, temps, strict=True):
loop over a dict .items() for region, total in revenue.items():
loop backward reversed(seq) for t in reversed(temps):
read an optional key d.get(key, default) c.get("phone") or "no phone"
count d[k] = d.get(k, 0) + 1 or Counter Counter(statuses).most_common(3)
group d.setdefault(k, []).append(v) or defaultdict(list) by_sensor.setdefault(sid, []).append(t)
merge settings, later wins a | b config = DEFAULTS | overrides
build a list, dict or set a comprehension [t for t in temps if t < 30]
total, count, min, max without a list a generator expression sum(q > 1 for q in quantities)
test “at least one” / “every” any() / all() any(r["status"] == "fail" for r in rows)
first match or None next(gen, None) next((r for r in rows if r["id"] == "S4"), None)
swap two values tuple unpacking low, high = high, low
split off first and last star unpacking first, *middle, last = sorted(temps)
join strings sep.join(parts) ", ".join(names)
build a path Path / "name" Path("data") / "reports"
list files sorted(folder.glob("*.csv")) [p.stem for p in sorted(folder.glob("*.csv"))]
open a file safely with path.open() as f: with path.open(encoding="utf-8") as f:
debug-print a value f"{expr=}" f"{total=}" → total=14162.33
parse text that may be bad EAFP: try / except ValueError try: x = float(s) except ValueError: x = None
skip blank lines LBYL if not line.strip(): continue
compare floats math.isclose(a, b) math.isclose(total, 672.3)
compare with zero abs_tol math.isclose(x, 0, abs_tol=1e-9)
exact money Decimal("…") and quantize() amount.quantize(Decimal("0.01"), ROUND_HALF_UP)
test for missing is None; NaN with math.isnan() if value is None:
remove items from a list a comprehension temps = [t for t in temps if t != -999.0]
default to a new list None sentinel def f(x, seen=None): seen = [] if seen is None else seen
make functions in a loop a factory or a default make_check(limit), lambda t, limit=limit: t > limit
lint / auto-fix ruff check / ruff check --fix ruff check --output-format concise .
format / check the format ruff format / ruff format --check ruff format --diff script.py
explain a rule ruff rule CODE ruff rule B006
silence one rule on one line # noqa: CODE import pandas as pd # noqa: F401
refactor safely record output, change one thing, compare assert report_after() == expected
Instead of Write
for i in range(len(xs)): x = xs[i] for x in xs:
i = 0 … i += 1 in a loop for i, x in enumerate(xs):
for i in range(len(a)): a[i], b[i] for x, y in zip(a, b, strict=True):
for k in d: v = d[k] for k, v in d.items():
for i in range(len(xs) - 1, -1, -1): for x in reversed(xs):
found = False … break found = any(cond(x) for x in xs)
ok = True … ok = False; break ok = all(cond(x) for x in xs)
n = 0 … if cond: n += 1 n = sum(cond(x) for x in xs)
ids = ["S1", "S2", "S3", "S4"]
temps = [20.21, 22.3, 19.4, 24.52]
for n, (sensor_id, temp) in enumerate(zip(ids, temps, strict=True), start=1):
print(n, sensor_id, temp) # number, then the pair
print(any(t > 24 for t in temps), all(t > 19 for t in temps)) # one? every?
print(sum(t > 20 for t in temps)) # count of True
Output
1 S1 20.21
2 S2 22.3
3 S3 19.4
4 S4 24.52
True True
3
from collections import Counter, defaultdict
rows = [("S1", "ok"), ("S2", "warn"), ("S1", "ok"), ("S4", "fail"), ("S2", "ok")]
counts: dict[str, int] = {}
groups: dict[str, list[str]] = {}
for sensor_id, status in rows:
counts[status] = counts.get(status, 0) + 1 # count
groups.setdefault(sensor_id, []).append(status) # group
print(counts)
print(groups)
print(Counter(s for _, s in rows).most_common(1)) # the same count, sorted
by_status = defaultdict(list) # a missing key starts as []
for sensor_id, status in rows:
by_status[status].append(sensor_id)
print(dict(by_status))
print({"unit": "C", "interval": 10} | {"unit": "F"}) # merge: the right side wins
Output
{'ok': 3, 'warn': 1, 'fail': 1}
{'S1': ['ok', 'ok'], 'S2': ['warn', 'ok'], 'S4': ['fail']}
[('ok', 3)]
{'ok': ['S1', 'S1', 'S2'], 'warn': ['S2'], 'fail': ['S4']}
{'unit': 'F', 'interval': 10}
Method Missing key Changes the dict
d[k] raises KeyError no
d.get(k, default) returns default (or None) no
d.setdefault(k, default) inserts default, returns it yes
defaultdict(factory)[k] inserts factory(), returns it yes
Counter()[k] returns 0 no
Form Builds Example
[expr for x in it if cond] list [float(t) for t in raw if t]
{k: v for k, v in pairs} dict {p.stem: p for p in paths}
{expr for x in it} set {r["region"].strip() for r in rows}
(expr for x in it) lazy generator sum(len(line) for line in f)

Rules of thumb:

  • At most two for clauses and one if in one comprehension. Otherwise use a loop or helper functions.
  • No side effects in a comprehension: [print(x) for x in xs] builds a list of None. Use a loop.
  • Pass a generator straight to sum(), min(), max(), any(), all(), sorted() or "".join(): max(t for t in temps if t < 30).
  • any([]) is False, all([]) is True. Check for empty data first.
low, high = 19.0, 23.0
low, high = high, low # swap
first, *middle, last = [19.4, 20.21, 22.3, 24.52] # star takes the rest
date, time, level, *message = "2024-05-01 08:04:17,625 DEBUG [cache] hit 0.78".split()
for sensor_id, (lo, hi) in {"S1": (19.0, 23.0)}.items(): # nested
print(sensor_id, lo, hi)
print(low, high, first, middle, last, level, message)
Output
S1 19.0 23.0
23.0 19.0 19.4 [20.21, 22.3] 24.52 DEBUG ['[cache]', 'hit', '0.78']
Pattern Meaning
a, b = b, a swap
_, b = pair ignore one value
head, *tail = xs first item and a list of the rest
*_, last = line.split(",") only the last field
for k, (x, y) in d.items(): nested unpacking in a loop
f(*args, **kwargs) unpack into a call (module 05)
Instead of Write Why
"x: " + str(x) f"x: {x}" one template
"%.2f" % x, "{:.2f}".format(x) f"{x:.2f}" ruff UP031, UP032
s += part in a loop "".join(parts) one copy instead of many
s[:3] == "abc" s.startswith("abc") says what it means
s.replace("$", "") for a prefix s.removeprefix("$") removes only the start
os.path.join(a, b) Path(a) / b ruff PTH118
os.listdir() + endswith(".csv") folder.glob("*.csv") one call, Path results
name.replace(".csv", "") path.stem safe for any name
f = open(p) … f.close() with p.open() as f: ruff SIM115; closes on errors
open(p).read() p.read_text(encoding="utf-8") one call, file closed
LBYL (look before you leap) EAFP (ask forgiveness)
Shape if can_do: do() try: do() except Error: ...
Best when the failure is common, and the check is cheap and exact; the check is a business rule only the operation knows what is valid; the world can change between check and act
Risk the check and the operation drift apart; race conditions a broad except hides bugs
Data example if not line.strip(): continue try: price = float(text) except ValueError: price = None
import math
def parse_price(text: str) -> float | None:
"""EAFP for parsing; keep the try to the one line that can fail."""
try:
return float(text.removeprefix("$").replace(",", ""))
except ValueError:
return None
prices = [parse_price(t) for t in ["$79.99", "$1,299.00", "N/A", "", "-"]]
valid = [p for p in prices if p is not None and math.isfinite(p) and p > 0] # LBYL rule
print(prices, valid)
Output
[79.99, 1299.0, None, None, None] [79.99, 1299.0]
  • Catch the narrowest exception: ValueError, KeyError, FileNotFoundError. Never a bare except:.
  • Put the code that uses the result in else: or after the try statement.
  • For optional dict keys, use d.get(): neither LBYL nor EAFP.
  • After EAFP parsing, still check the value: float() accepts "nan", "inf", "-5" and "1e3".
Kind Style Example
variable, function, module snake_case monthly_charges, read_rows(), clean_sales.py
class PascalCase SensorReading
constant UPPER_SNAKE_CASE MAX_QUANTITY = 50
internal _leading_underscore _parse_line()
clash with a keyword trailing_underscore_ class_
never l, O, I as names they look like 1 and 0
Rule Good Bad (ruff code)
compare with None x is None x == None (E711)
compare with booleans if flag: if flag == True: (E712)
empty sequence if not rows: if len(rows) == 0:
negative membership if k not in d: if not k in d: (E713)
type check isinstance(x, float) type(x) == float (E721)
one statement per line two lines if x: return (E701)
one import per line import os / import sys import os, sys (E401)
no bare except except ValueError: except: (E722)
lambda assignment def f(x): ... f = lambda x: ... (E731)
line length 79 (PEP 8) or 88 (ruff, Black) longer lines (E501)
blank lines 2 around top-level def/class, 1 between methods ruff format fixes it
imports top of file; standard library, third-party, local I001
Command Does
ruff check . lint the folder
ruff check --output-format concise file.py one line per finding
ruff check --fix . apply safe fixes
ruff check --fix --unsafe-fixes . also apply unsafe fixes (review the diff)
ruff check --diff file.py show fixes, change nothing
ruff check --select B,UP file.py only some rule families
ruff check --statistics . count the findings per rule
ruff format . reformat
ruff format --check . report files that would change (for CI)
ruff format --diff file.py show the formatting changes
ruff rule B006 the documentation of one rule
Prefix Family Typical codes
E, W pycodestyle E501 long line, E701 two statements, E711/E712 comparisons, E722 bare except, W291 trailing whitespace
F Pyflakes F401 unused import, F821 undefined name, F841 unused variable, F632 is with a literal
I isort I001 unsorted imports
B flake8-bugbear B006 mutable default, B008 function call in a default, B023 loop variable in a closure, B905 zip() without strict
UP pyupgrade UP006 List → list, UP045 Optional[X] → X | None, UP031/UP032 old formatting
SIM flake8-simplify SIM115 open() without with, SIM108 use a conditional expression
PTH flake8-use-pathlib PTH118 os.path.join, PTH123 open()
pyproject.toml
[tool.ruff]
line-length = 88
target-version = "py312"
extend-exclude = ["legacy/"] # folders or files to skip in folder runs
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "PTH"]
ignore = ["E501"] # let the formatter handle line length
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["B011"] # rules to skip for some files
  • Default rules: only E4, E7, E9 and F. Select more on purpose.
  • [*] in the output marks a safe automatic fix.
  • A file named on the command line is checked even if exclude lists it; a folder run skips it.
  • # noqa: B006 silences one rule on one line; # ruff: noqa on its own line silences a whole file. Prefer fixing.
Gotcha Wrong Right
mutable default def f(x, out=[]): def f(x, out=None): then out = [] if out is None else out
late binding [lambda: n for n in range(3)] → all return 2 [lambda n=n: n for n in range(3)] or a factory
is for values status is "fail", n is 1000 status == "fail"; is only for None, True, False
NaN x == float("nan") is always False math.isnan(x); pandas .isna()
float == 0.1 * 3 == 0.3 is False math.isclose(0.1 * 3, 0.3)
float near zero math.isclose(5.5e-17, 0) is False math.isclose(x, 0, abs_tol=1e-9)
running total t += x collects error sum(xs) (compensated since 3.12) or math.fsum(xs)
money rounding round(2.675, 2) is 2.67 Decimal("2.675").quantize(Decimal("0.01"), ROUND_HALF_UP)
Decimal from a float Decimal(0.1) keeps the binary error Decimal("0.1")
mixing Decimal and float Decimal("1.5") * 0.9 → TypeError Decimal("1.5") * Decimal("0.9")
list changed in a loop for x in xs: xs.remove(x) skips items xs = [x for x in xs if keep(x)]
dict changed in a loop del d[k] inside for k in d → RuntimeError for k in list(d): or a dict comprehension
silent zip zip(a, b) drops extra items zip(a, b, strict=True)
empty all() all(...) of nothing is True also check that the data is not empty
next() with no match StopIteration next(gen, None)
or for defaults c.get("n") or 10 replaces a real 0 c.get("n", 10) when 0 is a valid value
:.1% multiplies by 100 itself do not multiply first
def tag(item, tags=[]): # gotcha: one shared list
tags.append(item)
return tags
tag("vip")
funcs = [lambda: n for n in range(3)] # gotcha: late binding
codes = [-999, -999, 21]
for c in codes: # gotcha: changing the list during the loop
if c == -999:
codes.remove(c)
print(tag("new"), [f() for f in funcs], codes, 0.1 * 3 == 0.3)
Output
['vip', 'new'] [2, 2, 2] [-999, 21] False
  1. Run the old code. Record its output (python old.py > expected.txt, or keep the returned lines).
  2. Lint it: ruff check --output-format concise old.py. Note the bugs (B, E722, F821). Finish the refactor with the same output, then fix each bug in its own visible change.
  3. Change one thing: file handling, then counting, then formatting.
  4. Compare after each change: diff expected.txt <(python new.py), or assert new() == expected.
  5. Keep format “improvements” separate. round(x, 2) → f"{x:.2f}" turns 8533.4 into 8533.40.
  6. Finish with ruff check and ruff format --check. Keep the comparison as a test (module 14).