Idioms and gotchas
Pythonic code uses the language’s own tools: direct iteration, unpacking, comprehensions, context managers and the standard library. This page lists the idioms as “instead of… write…”, then shows each classic trap with a small demo, its symptom and its fix.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| loop over items | the items, not indexes | for row in rows: |
| a counter in a loop | enumerate(xs, start=1) |
for n, line in enumerate(f, start=1): |
| two lists in step | zip(a, b, strict=True) |
for sid, t in zip(ids, temps, strict=True): |
| keys and values | d.items() |
for k, v in d.items(): |
| a default for a missing key | d.get(k, default) |
cfg.get("timeout", 30) |
| build a list from a loop | a comprehension | [p.stem for p in paths if p.suffix == ".csv"] |
| sum or count without a list | a generator expression | sum(r["qty"] for r in rows) |
| “is there any…?” / “are all…?” | any() / all() |
any(t > 30 for t in temps) |
the first match or None |
next(gen, None) |
next((r for r in rows if r["id"] == k), None) |
| swap values | tuple unpacking | a, b = b, a |
| head and rest | star unpacking | first, *rest = items |
| join strings | sep.join(parts) |
", ".join(names) |
| format values | f-strings | f"{total:,.2f}"; f"{x=}" to debug |
| open a file | with |
with open(p, encoding="utf-8") as f: |
| build paths | pathlib.Path |
Path("data") / "sales.csv" |
| test a range | a chained comparison | if 0 <= pct <= 100: |
| test against several values | in with a tuple or set |
if level in {"WARNING", "ERROR"}: |
| choose a value inline | a conditional expression | label = "high" if x > 10 else "low" |
| assign and test at once | the walrus := |
while chunk := f.read(8192): |
| sort by a field | key= |
sorted(rows, key=itemgetter("revenue"), reverse=True) |
| the largest by a field | max(xs, key=...) |
max(stores, key=lambda s: s.size) |
| merge dicts | a | b |
config = DEFAULTS | overrides |
| count / group | Counter, defaultdict(list) |
Counter(levels).most_common(3) |
| ignore one expected error | contextlib.suppress |
with suppress(FileNotFoundError): p.unlink() |
| keep the original cause | raise ... from err |
raise ConfigError("bad file") from err |
| branch on the shape of data | match |
case {"status": 200, "items": items}: |
| a record class | @dataclass |
@dataclass(frozen=True) |
| an empty-container check | truthiness | if not rows: |
a None check |
is None |
if value is None: |
| a float comparison | math.isclose |
math.isclose(total, 0.3) |
| a fresh default list | a None sentinel |
seen = [] if seen is None else seen |
Pythonic idioms: bad → good
Section titled “Pythonic idioms: bad → good”| Instead of | Write | Why |
|---|---|---|
for i in range(len(xs)): print(xs[i]) |
for x in xs: print(x) |
direct iteration |
i = 0 … i += 1 |
for i, x in enumerate(xs): |
no manual counter |
for i in range(len(a)): f(a[i], b[i]) |
for x, y in zip(a, b, strict=True): |
strict catches length bugs |
for k in d: v = d[k] |
for k, v in d.items(): |
one lookup |
if k in d: v = d[k] else: v = 0 |
v = d.get(k, 0) |
one call |
d[k] = d[k] + 1 if k in d else 1 |
counts = Counter(xs) |
the standard tool |
if k not in d: d[k] = [] then d[k].append(v) |
d.setdefault(k, []).append(v) or defaultdict(list) |
|
out = [] + for + append |
out = [f(x) for x in xs if ok(x)] |
shorter, faster |
sum([x * x for x in xs]) |
sum(x * x for x in xs) |
no temporary list |
found = False + loop + break |
found = any(ok(x) for x in xs) |
intent is visible |
s = "" + s += part |
s = "".join(parts) |
one copy |
"Total: " + str(n) |
f"Total: {n}" |
readable |
"%.2f" % x, "{:.2f}".format(x) |
f"{x:.2f}" |
modern formatting |
f = open(p) … f.close() |
with open(p) as f: |
closes on errors too |
os.path.join(a, b), os.path.exists(p) |
Path(a) / b, p.exists() |
objects, not strings |
tmp = a; a = b; b = tmp |
a, b = b, a |
|
x = xs[0]; rest = xs[1:] |
x, *rest = xs |
|
if x > 0 and x < 10: |
if 0 < x < 10: |
chained comparison |
if c == "a" or c == "b" or c == "c": |
if c in {"a", "b", "c"}: |
|
if len(xs) == 0: |
if not xs: |
truthiness |
if flag == True: |
if flag: |
|
if x == None: |
if x is None: |
identity for singletons |
type(x) == int |
isinstance(x, int) |
accepts subclasses |
xs.sort(); top = xs[-1] |
top = max(xs) |
, no mutation |
sorted(xs, key=lambda r: r["k"]) |
sorted(xs, key=itemgetter("k")) |
faster, clearer |
try: v = d[k] except KeyError: v = None |
v = d.get(k) |
|
try: ... except: pass |
except SpecificError: or contextlib.suppress(...) |
does not hide bugs |
raise NewError(str(e)) |
raise NewError("context") from e |
keeps the traceback chain |
print("x =", x) while debugging |
print(f"{x=}") |
shows the expression |
lambda assigned to a name |
def |
a real name in tracebacks |
a = {**a, **b} |
a = a | b (a new dict) or a |= b |
|= mutates the dict: other names that refer to it see the change |
if/elif on dict keys and types |
match with mapping and class patterns |
structure is visible |
a class with only __init__ storing fields |
@dataclass |
free __repr__, __eq__ |
global counter in functions |
return values, or a class | testable |
from collections import Counterfrom operator import itemgetter
rows = [ {"store": "S01", "region": "North", "revenue": 304.09}, {"store": "S07", "region": "East", "revenue": 2598.0}, {"store": "S10", "region": "West", "revenue": 66.49},]for n, row in enumerate(rows, start=1): print(n, row["store"], f"{row['revenue']:>9,.2f}")best = max(rows, key=itemgetter("revenue"))print(best["store"], any(r["revenue"] > 1000 for r in rows))print(sum(r["revenue"] for r in rows))first, *others = sorted(r["store"] for r in rows)print(first, others, Counter(r["region"] for r in rows).most_common(1))print(next((r["store"] for r in rows if r["region"] == "South"), None))config = {"timeout": 30, "retries": 3} | {"retries": 5}print(config, f"{len(rows)=}")1 S01 304.092 S07 2,598.003 S10 66.49S07 True2968.58S01 ['S07', 'S10'] [('North', 1)]None{'timeout': 30, 'retries': 5} len(rows)=3def describe(response: dict) -> str: match response: # structural pattern matching case {"status": 200, "items": [first, *_]}: return f"ok, first item {first}" case {"status": 200, "items": []}: return "ok, empty" case {"status": 429 | 503 as code}: return f"retry later ({code})" case _: return "unexpected"
print(describe({"status": 200, "items": ["P001", "P002"]}))print(describe({"status": 429}), "|", describe({"status": 200, "items": []}))ok, first item P001retry later (429) | ok, emptyEAFP and LBYL
Section titled “EAFP and LBYL”EAFP means “easier to ask forgiveness than permission”: try the operation and handle the exception. LBYL means “look before you leap”: check first, then act.
| LBYL | EAFP | |
|---|---|---|
| shape | if path.exists(): read(path) |
try: read(path) except FileNotFoundError: ... |
| best when | the check is cheap, exact and a business rule | only the operation itself knows what is valid |
| risk | the world changes between check and act (race) | a broad except hides real bugs |
| typical uses | blank lines, value ranges, permissions | parsing numbers and dates, files, dict keys, network calls |
import math
def parse_price(text: str) -> float | None: try: # EAFP: float() knows every valid spelling value = float(text.strip().removeprefix("$").replace(",", "")) except ValueError: return None else: # runs only when no exception happened return value if math.isfinite(value) and value >= 0 else None # LBYL rules
print([parse_price(t) for t in ["$79.99", "$1,299.00", "N/A", "nan", "-5"]])[79.99, 1299.0, None, None, None]Keep the try block to the one line that can fail. Catch the narrowest exception. Put the follow-up code in else:.
Gotchas
Section titled “Gotchas”Six classic traps have their full demo on the page where the concept is taught. This table gives the symptom, the fix and the link. The traps after it have their demo here; demos with deliberately bad code say so in a comment.
| Trap | Symptom | Fix | Demo |
|---|---|---|---|
mutable default argument def f(x, out=[]) |
state leaks between calls | default to None, create the list inside (ruff B006) |
defaults |
late binding: [lambda: n for n in range(3)] |
every function sees the last loop value | bind now: lambda n=n: n, partial or a factory (ruff B023) |
closures |
total += x inside a function |
UnboundLocalError: cannot access local variable 'total' |
return the new value, or keep state in an object | scope |
b = a, [[0] * 3] * 3, copy.copy of nested data |
a change to the “copy” changes the original | a comprehension per row; copy.deepcopy |
copying and aliasing |
0.1 + 0.2 == 0.3, round(2.675, 2), round(2.5) |
False, 2.67, 2 |
math.isclose, Decimal("..."); halves round to even |
numbers, rounding |
x == 1 or 2 |
always truthy | x in (1, 2) |
syntax gotchas |
is versus ==
Section titled “is versus ==”a = "hello world"b = " ".join(["hello", "world"]) # built at runtime: a different objectprint(a == b, a is b) # equal values, different objectsx = [1, 2]y = x # the same object, not a copyz = [1, 2] # an equal, separate listprint(y is x, z is x, z == x)True FalseTrue False TrueSymptom: a comparison works in one place and fails in another. Fix: == compares values; is compares identity. Use is only for None, True, False and sentinels. x is "text" with a literal triggers a SyntaxWarning.
Integer caching
Section titled “Integer caching”small_a, small_b = int("256"), int("256")big_a, big_b = int("257"), int("257")print(small_a is small_b, big_a is big_b, big_a == big_b)True False TrueSymptom: is seems to work for small numbers and then fails. CPython keeps one shared object for each integer from -5 to 256, so is happens to be True there. Constants inside one script can also be shared. Fix: never compare numbers or strings with is.
Changing a collection while looping over it
Section titled “Changing a collection while looping over it”codes = [-999, -999, 21, 22]for c in codes: # bad: removing shifts the items under the loop if c == -999: codes.remove(c)print(codes)
codes = [-999, -999, 21, 22]codes = [c for c in codes if c != -999] # build a new listprint(codes)[-999, 21, 22][21, 22]stock = {"P001": 0, "P002": 5, "P003": 0}for product_id in stock: # bad: the dict changes size during iteration if stock[product_id] == 0: del stock[product_id]RuntimeError: dictionary changed size during iterationstock = {"P001": 0, "P002": 5, "P003": 0}for product_id in list(stock): # loop over a copy of the keys if stock[product_id] == 0: del stock[product_id]print(stock, {k: v for k, v in {"a": 0, "b": 1}.items() if v}){'P002': 5} {'b': 1}Symptom: a list loop silently skips items; a dict or set loop raises RuntimeError. Fix: build a new collection with a comprehension, or loop over a copy (list(d), xs[:]).
Chained comparisons
Section titled “Chained comparisons”x = 5print(1 < x < 10, (1 < x) < 10) # same result here, by luckprint(3 > 2 > 1, (3 > 2) > 1) # 3 > 2 and 2 > 1, versus True > 1print(1 < 3 > 2) # legal: means 1 < 3 and 3 > 2True TrueTrue FalseTrueSymptom: adding parentheses changes the answer; a < b > c reads strangely. a < b < c means a < b and b < c, while (a < b) < c compares a bool with c. Fix: use chains only for ranges (low <= x <= high); write other combinations with and.
Bare except:
Section titled “Bare except:”import sys
def stop() -> None: sys.exit(1) # raises SystemExit
try: stop()except: # bad: also catches SystemExit and KeyboardInterrupt (Ctrl+C) print("bare except swallowed the exit")
try: try: stop() except Exception: # better: SystemExit is not an Exception subclass print("not printed")except SystemExit as exit_request: print("exit passed through with code", exit_request.code)bare except swallowed the exitexit passed through with code 1Symptom: Ctrl+C does not stop the program, sys.exit() is ignored, and typos such as NameError vanish. Fix: catch the specific exception (ValueError, KeyError, OSError); use except Exception as err: plus logging only at the top level of a program (ruff E722).
Methods that return None
Section titled “Methods that return None”prices = [249.0, 14.99, 79.99]result = prices.sort() # bad: sorts in place and returns Noneprint(result, prices, sorted([3, 1, 2]))None [14.99, 79.99, 249.0] [1, 2, 3]Symptom: a variable is unexpectedly None. In-place methods (list.sort, list.append, dict.update, random.shuffle) return None. Fix: use the in-place call alone, or the copying form (sorted, a | b).
More traps
Section titled “More traps”More number and truthiness traps (bool("False"), -7 // 2, money rounding) are on the syntax and types page.
| Trap | Symptom | Fix |
|---|---|---|
int("3.5") |
ValueError |
int(float("3.5")), or Decimal |
["a" "b", "c"] |
a missing comma joins strings: ['ab', 'c'] |
one item per line, trailing commas |
zip(a, b) with different lengths |
extra items vanish silently | zip(a, b, strict=True) |
| a generator used twice | the second pass is empty | store a list, or call the function again |
a class attribute items = [] |
all instances share one list | create it in __init__ or with field(default_factory=list) |
t = ([1],); t[0] += [2] |
TypeError, but the list changed anyway |
t[0].append(2) |
except E as err: then err after the block |
NameError: err is deleted |
save it: error = err |
__eq__ defined without __hash__ |
instances become unhashable | @dataclass(frozen=True) or define __hash__ |
x == float("nan") |
always False |
math.isnan(x); pandas isna() |
datetime.now() |
naive local time | datetime.now(UTC) |
open() without encoding |
works on one OS, fails on another | encoding="utf-8" |
a file named random.py or pandas.py |
AttributeError from the real module |
rename your file |
from module import * |
names silently overwrite each other | explicit imports |
print instead of return |
the caller gets None |
return values; print at the edge |
a huge try block |
the wrong line’s error is caught | one risky line per try |
| recursion on deep data | RecursionError at about 1,000 levels |
a loop with an explicit stack |
sum() of floats in a loop by hand |
tiny drift versus sum |
sum (compensated since 3.12) or math.fsum |
Learn more
Section titled “Learn more”- Module 13 lesson: Pythonic code and its cheat sheet
- Module 04: data structures for copies and mutability
- Module 05: functions for defaults, scope and closures
- Module 06: errors and debugging for exceptions
- Module 01: Python basics for numbers and floats
- Master cheat sheet: collections and comprehensions, functions and scope, errors and debugging, standard library quick reference, tooling