unrust

Idiomatic Python: 10 patterns with examples

Published

By the Unrust team · 15 min read · Editorial method

Ten idiomatic Python patterns, each run on CPython 3.11 to 3.15 with its real output and one trap where the idiom differs from the code it replaces.

What is idiomatic Python?

Idiomatic Python is code that uses the language's own constructs, such as looping over items directly, enumerate, unpacking, truth-value tests and try/except, instead of habits carried over from other languages. The Python glossary calls this Pythonic. It is a convention, not a speed rule: each section below shows where an idiom behaves differently.

Every example below, apart from the timing script near the end, was run with CPython 3.11.18, 3.12.16, 3.13.18, 3.14.10 and 3.15.2 on November 16, 2026, and the comments quote what Python printed. The output is identical on all five versions except for two differences that the text points out. When a snippet ends in an error, the comment is the last line of the traceback.

The table is the short version. Each row is one section below: the habit to drop, the idiom to prefer, and the one case where the two do not behave the same.

#   Instead of                    Prefer                                       What it buys / trap
--  ----------------------------  -------------------------------------------  --------------------------------------------------------
1   range(len(xs)) and xs[i]      for x in xs; enumerate(xs, 1)                No counter. Trap: removing items mid-loop skips one
2   len(xs) == 0; x == None       if not xs; x is None                         States intent. Trap: 0 and "" are falsy too
3   xs[i] with ys[i]              zip(xs, ys, strict=True)                     No index. Trap: plain zip drops extras silently
4   xs[0], xs[1:]; temp swap      first, *rest = xs; a, b = b, a               No temporary. Trap: [] raises ValueError, not IndexError
5   if k in d: d[k] += 1 ...      Counter(xs); defaultdict(list)               No branch per key. Trap: defaultdict inserts on a read
6   if path.exists(): open(p)     try: p.read_text() except FileNotFoundError  No race, auto-close. Trap: a wide try hides bugs
7   flag and break loop           all(...); any(...) on a generator            Stops at first hit. Trap: all() of nothing is True
8   s += x + ", "; "a=" + str(a)  ", ".join(xs); f"{a=}"                       Linear time. Trap: join takes only strings
9   type(x) == int                isinstance(x, int)                           Accepts subclasses. Trap: True is an int
10  sorted(xs, key=k)[-1]         max(xs, key=k, default=None)                 No full sort. Trap: ties pick a different item

1. Loop over the items; let enumerate count

Loop over the items themselves, and reach for enumerate when you also need a number. The Python glossary offers for i in range(len(food)) as its example of non-Pythonic code, set against the cleaner for piece in food. enumerate(names, start=1) hands you the count and the item together, and unlike a range built from len() it also works on a generator.

The trap: looping directly over a list that you change skips items. In the last example, removing the first "bad" shifts the second one into the slot the loop has already passed, so one "bad" survives and Python raises nothing. The index loop fails loudly in the same situation, with IndexError, because range(len(jobs)) was fixed before the loop started. Loop over a copy such as jobs[:], or build a new list.

names = ["Ada", "Grace", "Linus"]

# Before: a counter loop, the habit the Python glossary calls non-Pythonic
for i in range(len(names)):
    print(i + 1, names[i])
# 1 Ada
# 2 Grace
# 3 Linus

# After: loop over the items; enumerate supplies the count and prints the same three lines
for n, name in enumerate(names, start=1):
    print(n, name)

# Trap: removing from a list while looping over it skips the next item
jobs = ["a", "bad", "bad", "b"]
for job in jobs:
    if job == "bad":
        jobs.remove(job)
print(jobs)  # ['a', 'bad', 'b']

2. Test truth values directly; use is None for None

Test the object itself: if not items instead of if len(items) == 0, and x is None instead of x == None. PEP 8 recommends both. Empty sequences are false, so test them directly, and comparisons to singletons like None should always be done with is or is not, never the equality operators.

The trap: truthiness is wider than emptiness. Zero, 0.0 and the empty string are false too, so if not requested replaced a caller's 0 with the default in page_size. PEP 8 warns about this exact slip: beware of writing if x when you really mean if x is not None. The == None form has a failure of its own, because it calls __eq__, and the AlwaysEqual class answers True to anything.

items = []

# Before
if len(items) == 0:
    print("no items")  # no items

# After: same output
if not items:
    print("no items")

# Trap: 0 and "" are falsy too, so truthiness cannot tell zero from missing
def page_size(requested=None):
    if not requested:
        return 25
    return requested

print(page_size(0))  # 25

# Fix: ask the exact question with is None
def page_size_fixed(requested=None):
    if requested is None:
        return 25
    return requested

print(page_size_fixed(0))  # 0

# Why is and not ==: a class decides what == None means
class AlwaysEqual:
    def __eq__(self, other):
        return True

probe = AlwaysEqual()
print(probe == None, probe is None)  # True False

3. Pair sequences with zip, and decide what a leftover means

Walk two sequences together with zip instead of indexing both with one counter. It yields tuples, accepts any iterable and removes the index variable. The Python documentation recommends strict=True when the inputs are assumed to have the same length.

The trap: by default zip stops at the shorter input and says nothing, so the missing score removed Linus from the result without a word. The index loop it replaced raised IndexError for the same input. With strict=True the same call raises ValueError: zip() argument 2 is shorter than argument 1. The argument was added in Python 3.10, and Python 3.9 rejects it with TypeError: zip() takes no keyword arguments, so check requires-python first.

names = ["Ada", "Grace", "Linus"]
scores = [91, 78, 85]

# Before
for i in range(len(names)):
    print(names[i], scores[i])
# Ada 91
# Grace 78
# Linus 85

# After: same three lines
for name, score in zip(names, scores):
    print(name, score)

# Trap: with unequal lengths, zip stops at the shorter input and says nothing
scores = [91, 78]
print(list(zip(names, scores)))  # [('Ada', 91), ('Grace', 78)]

# Fix (Python 3.10 and later): a length mismatch becomes an error
list(zip(names, scores, strict=True))
# ValueError: zip() argument 2 is shorter than argument 1

4. Unpack instead of indexing and swapping through a temporary

Unpack a sequence into names, and swap with a, b = b, a. first, *rest = items replaces items[0] and items[1:] in one line, and a swap needs no temporary because Python evaluates the whole right-hand side before it assigns to any name on the left.

The trap: the failure changes type. items[0] on an empty list raises IndexError, but first, *rest = [] raises ValueError, so an except IndexError wrapped around the old code no longer catches the new one. Catch ValueError, or test if items first.

items = [10, 20, 30]

# Before
first = items[0]
rest = items[1:]
a, b = 1, 2
tmp = a
a = b
b = tmp
print(first, rest, a, b)  # 10 [20, 30] 2 1

# After (the swap undoes the one above)
first, *rest = items
a, b = b, a
print(first, rest, a, b)  # 10 [20, 30] 1 2

# Trap: an empty list raises ValueError when unpacked, not the IndexError that items[0] raised
try:
    [][0]
except IndexError as err:
    print("indexing:", err)  # indexing: list index out of range

try:
    first, *rest = []
except ValueError as err:
    print("unpacking:", err)  # unpacking: not enough values to unpack (expected at least 1, got 0)

5. Count and group with Counter and defaultdict

Let the collections module do the bookkeeping. Counter(words) replaces the loop that tests whether each key is already in the dict, and defaultdict(list) replaces the test before each append to a group. For a single lookup with a fallback, counts.get(key, 0) is enough.

The trap: a read can write. counts["z"] returns 0 and leaves the Counter alone, but by_letter["Z"] on a defaultdict creates the key, so "Z" in by_letter is True afterwards. The documentation says __missing__ inserts the default value for the key and returns it. Use .get() or in when you only want to look.

from collections import Counter, defaultdict

words = ["b", "a", "b", "c", "b"]

# Before
counts = {}
for w in words:
    if w in counts:
        counts[w] += 1
    else:
        counts[w] = 1
print(counts)  # {'b': 3, 'a': 1, 'c': 1}

# After
counts = Counter(words)
print(counts)  # Counter({'b': 3, 'a': 1, 'c': 1})

# Grouping: names by first letter
people = ["Ada", "Alan", "Grace", "Linus", "Lin"]
by_letter = defaultdict(list)
for person in people:
    by_letter[person[0]].append(person)
print(dict(by_letter))  # {'A': ['Ada', 'Alan'], 'G': ['Grace'], 'L': ['Linus', 'Lin']}

# Trap: a read can write. Counter returns 0 for a missing key; defaultdict creates it
print(counts["z"], "z" in counts)        # 0 False
print(by_letter["Z"], "Z" in by_letter)  # [] True

6. Python idiomatic error handling: try, then catch one failure (EAFP)

Idiomatic Python handles errors with EAFP, easier to ask for forgiveness than permission: attempt the operation and catch the specific exception, instead of testing first. The Python glossary contrasts it with LBYL, look before you leap, and notes that in a multi-threaded environment LBYL can risk a race condition between the looking and the leaping. Path.read_text also opens and closes the file for you, so the manual close disappears; for a file you read line by line, with path.open(encoding="utf-8") as handle closes it the same way, even if the loop raises.

The gap is easy to simulate. The glossary's example is a second thread removing a dictionary key; here a second process deletes a file. In the example, path.exists() returned True, the file was deleted before the read, and the read still raised FileNotFoundError, so the check protected nothing and the except clause was needed anyway.

The trap: keep the try block as small as the call that can fail. A wide try block also catches the KeyError raised inside total(), so a missing price is reported as order not found. PEP 8 says to limit the try clause to the absolute minimum amount of code necessary, and shows the rest going in an else clause.

from pathlib import Path

path = Path("settings.txt")

# Before: check first, then open and close by hand
if path.exists():
    f = open(path)
    text = f.read()
    f.close()
else:
    text = ""

# After: pathlib opens and closes the file; catch the one failure you expect
try:
    text = path.read_text(encoding="utf-8")
except FileNotFoundError:
    text = ""
print(repr(text))  # ''

# Why: the check can be stale by the time the file is read
path.write_text("debug=1", encoding="utf-8")
looked = path.exists()
path.unlink()  # another process deletes the file after the check
try:
    path.read_text(encoding="utf-8")
except FileNotFoundError:
    print(looked, "but the read still failed")  # True but the read still failed

# Trap: a wide try block reports the wrong problem
orders = {"a": {"qty": 2}}

def total(order):
    return order["qty"] * order["price"]  # bug: there is no "price" key

try:
    result = total(orders["a"])
except KeyError:
    result = "order not found"
print(result)  # order not found

7. Use any() and all() on a generator expression

Replace a flag-and-break loop with all() or any() over a generator expression. Without square brackets the generator is lazy, so any() stops at the first true item: in the code below, check was called for 1 and 2 only. With brackets, the list comprehension called it for all three items before any() saw a result.

The trap: all() of an empty iterable is True, and any() of an empty iterable is False. A guard such as if all(order["paid"] for order in orders) therefore passes when orders is empty. The documentation describes all() as returning True if all elements are true, or if the iterable is empty. Check for emptiness first when an empty input should not pass.

orders = [
    {"id": 1, "paid": True},
    {"id": 2, "paid": False},
    {"id": 3, "paid": True},
]

# Before
all_paid = True
for order in orders:
    if not order["paid"]:
        all_paid = False
        break
print(all_paid)  # False

# After: same result
all_paid = all(order["paid"] for order in orders)
print(all_paid)

# Without brackets any() stops at the first hit; with brackets the whole list is built first
calls = []

def check(n):
    calls.append(n)
    return n > 1

print(any([check(n) for n in (1, 2, 3)]), calls)  # True [1, 2, 3]
calls.clear()
print(any(check(n) for n in (1, 2, 3)), calls)    # True [1, 2]

# Trap: all() of nothing is True, so an empty orders list passes
print(all(order["paid"] for order in []))  # True
print(any(order["paid"] for order in []))  # False

8. Build strings with join and f-strings

Join a sequence with ", ".join(parts) instead of adding pieces to a string in a loop, and format values with f-strings. join leaves no trailing separator to trim, and PEP 8 recommends the ''.join() form where speed matters because it keeps concatenation in linear time across various implementations. f"{total=}", added in Python 3.8, prints the expression, an equals sign and the repr of the value, which makes a quick debugging line.

The trap: join accepts only strings. A list of ints raises TypeError: sequence item 0: expected str instance, int found, so convert first with str(i) for i in ids. The same repr rule means f"{name=}" keeps the quotes: name='Ada'.

parts = ["ada", "grace", "linus"]

# Before
line = ""
for part in parts:
    line += part + ", "
line = line[:-2]
print(line)  # ada, grace, linus

# After: same text
line = ", ".join(parts)
print(line)

# Formatting values (the = form needs Python 3.8 or later)
total = 42
name = "Ada"
print("total = " + str(total))  # total = 42
print(f"{total=}", f"{name=}")  # total=42 name='Ada'

# Trap: join accepts only strings
ids = [3, 11, 17]
try:
    ", ".join(ids)
except TypeError as err:
    print(err)  # sequence item 0: expected str instance, int found
print(", ".join(str(i) for i in ids))  # 3, 11, 17

9. Check types with isinstance, not type() ==

Use isinstance(value, int) instead of type(value) == int. PEP 8 says object type comparisons should always use isinstance(), and isinstance accepts subclasses, so the Count class that inherits from int passes. From Python 3.10 you can test several types in one call with a union, as in isinstance(x, int | float).

The trap: bool is a subclass of int, so isinstance(True, int) is True, while type(True) == int evaluates to False. If True should not count as a number, rule it out first: isinstance(value, int) and not isinstance(value, bool).

class Count(int):
    pass

# Before
def is_count(value):
    return type(value) == int

print(is_count(Count(3)))  # False

# After
def is_count(value):
    return isinstance(value, int)

print(is_count(Count(3)))  # True

# Trap: bool is a subclass of int, so True and False pass as counts
print(is_count(True))  # True

# Several types in one call (Python 3.10 and later)
print(isinstance(2.5, int | float))  # True

10. Find an extreme with max, min and key=

Ask for the extreme directly: max(words, key=len) instead of sorting everything and taking the last element. key says what to compare, and default= says what to return for an empty input; default was added in Python 3.4.

The trap: ties. sorted(words, key=len)[-1] returned pear, the last of the three four-letter words, while max(words, key=len) returned plum, the first. The documentation says max returns the first maximal item, consistent with sorted(..., reverse=True)[0] and not with sorted(...)[-1]. Without default=, max() of an empty list raises ValueError, and Python 3.11 words the message max() arg is an empty sequence.

words = ["fig", "plum", "kiwi", "pear"]

# Before: sort everything and take the last element
print(sorted(words, key=len)[-1])  # pear

# After: three words tie at four letters, and max returns the first of them
print(max(words, key=len))  # plum

# default= answers the empty case
print(max([], key=len, default="none"))  # none

# Trap: without default=, max() of nothing raises
max([], key=len)
# ValueError: max() iterable argument is empty

Quick check: which three lines would you flag?

total_by_name adds up scores per person. The limit argument caps how many rows to use: None means no cap, and 0 means none. Name the three lines that do not do what they appear to promise, then predict what the call at the bottom prints.

def total_by_name(names, scores, limit=None):
    if limit:
        names = names[:limit]
    totals = {}
    for name, score in zip(names, scores):
        try:
            totals[name] = totals.get(name, 0) + score
        except:
            continue
    return totals

print(total_by_name(["Ada", "Grace", "Linus", "Ada"], [91, "78", 85], limit=0))
Reveal the answer and explanation

It prints {'Ada': 91, 'Linus': 85}, although limit=0 asked for no rows. Flag if limit:, because 0 is falsy and is treated as no cap (pattern 2). Flag zip(names, scores), which stops after three scores and silently drops the second Ada (pattern 3). Flag the bare except:, which swallowed the TypeError from adding the string "78" to 0, so Grace vanished without a trace (tell 3).

The repair tests limit is not None, trims both lists, makes zip strict and removes the try, so each bad input fails at the line that caused it. The output in the comments is from the repaired function.

def total_by_name(names, scores, limit=None):
    if limit is not None:
        names, scores = names[:limit], scores[:limit]
    totals = {}
    for name, score in zip(names, scores, strict=True):
        totals[name] = totals.get(name, 0) + score
    return totals

print(total_by_name(["Ada", "Grace"], [91, 78], limit=0))  # {}
print(total_by_name(["Ada", "Grace", "Ada"], [91, 78, 9]))  # {'Ada': 100, 'Grace': 78}

try:
    total_by_name(["Ada", "Grace", "Linus", "Ada"], [91, 78, 85])
except ValueError as err:
    print(err)  # zip() argument 2 is shorter than argument 1

try:
    total_by_name(["Ada", "Grace"], [91, "78"])
except TypeError as err:
    print(err)  # unsupported operand type(s) for +: 'int' and 'str'

AI-written Python: 6 non-idiomatic tells

A diff from an AI assistant can look fluent and still carry habits from other languages or from older Python. The six tells below are search terms for a reviewer, not a claim about how often any tool writes them: Unrust has no primary data on that. Each row gives the fix and the question to ask before accepting the change. The Ruff column lists the stable Ruff rules that flagged each shape, checked with Ruff 0.17.5 on November 16, 2026.

Two more tells have their own posts: mutable default arguments and exhausted iterators (/blog/python-exhausted-iterators-and-mutable-defaults), and comprehensions written for their side effects (/blog/python-list-comprehensions). For a wider checklist on generated Python, see the review practice at /languages/python/reviewing-ai-generated-code.

#  Tell in the diff                    Idiomatic fix                        Ruff                  What the reviewer checks
-  ----------------------------------  -----------------------------------  --------------------  -------------------------------------------------
1  range(len(xs)) only to read xs[i]   for x in xs; enumerate(xs)           none                  Is xs changed in the loop? Is i used elsewhere?
2  x == None; flag == True             x is None; if flag:                  E711, E712            Can 0, "" or [] be a valid value?
3  except: / except Exception: pass    Catch the named error; log or raise  E722, BLE001, S110    Which failure is now silent? Ctrl-C too
4  assert used to validate input       if not ok: raise ValueError(...)     S101                  Must it still run under python -O?
5  utcnow(); typing.List; Optional[X]  now(UTC); list[...]; X | None        DTZ003, UP006, UP045  Which Python versions does requires-python allow?
6  type(x) == int; type(x) != str      isinstance(x, int)                   E721                  Should True count as an int? Subclasses?

Run the tells that only show up at runtime

Tells 2, 3, 4 and 5 are easiest to believe once you have seen them run, and the block below needs no files. Python 3.12 and later emit a DeprecationWarning for utcnow(); the block turns it into an exception so that it prints. Python 3.11 accepts utcnow() without a warning, and datetime.UTC needs 3.11 or later, so on older versions use timezone.utc.

import subprocess
import sys
import warnings
from datetime import UTC, datetime

# Tell 2: == True and truthiness ask different questions
flag = 2
print(flag == True, bool(flag))  # False True

# Tell 3: a bare except also swallows Ctrl-C
try:
    raise KeyboardInterrupt
except:
    print("swallowed KeyboardInterrupt")  # swallowed KeyboardInterrupt

# Tell 4: assert disappears under python -O
code = "assert False, 'bad input'; print('assert skipped')"
normal = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
optimized = subprocess.run([sys.executable, "-O", "-c", code], capture_output=True, text=True)
print(normal.stderr.splitlines()[-1])  # AssertionError: bad input
print(optimized.stdout.strip())        # assert skipped

# Tell 5: calls that newer Python versions deprecate
warnings.simplefilter("error")
try:
    datetime.utcnow()
except DeprecationWarning as err:
    print(err)
# datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
print(datetime.now(UTC).tzinfo)  # UTC

Let Ruff flag the mechanical ones

A linter can enforce part of this list. The configuration below selects the stable Ruff rules that flagged the matching shapes from sections 2, 3, 6, 7, 9 and 10 and from tells 2 to 6, run with Ruff 0.17.5 on November 16, 2026. B905, the zip check, only applies when target-version is 3.10 or later; on a 3.9 target Ruff stays silent about it.

Ruff did not flag the counter loop, len(items) == 0, the temporary swap, the counting branch, the += loop or the flag-and-break loop, even with --select ALL (ignoring only documentation, annotation, print, packaging, line-length and trailing-comma rules). Those are the lines a reviewer still has to read. S101 reports every assert, including the ones in tests, so you will probably ignore it for test files.

[tool.ruff]
target-version = "py311"

[tool.ruff.lint]
select = [
    "E711", "E712", "E721", "E722",  # == None, == True, type(x) ==, bare except
    "B905", "B006",                  # zip() without strict=, mutable default argument
    "UP",                            # typing.List and Optional, % and format() strings
    "PTH", "SIM115",                 # os.path calls, open() outside a with block
    "C419", "FURB192",               # any([...]), sorted(...)[-1]
    "BLE001", "S110", "S101",        # blind except, silent except, assert
    "DTZ003",                        # datetime.utcnow()
]

When not to be idiomatic

Idioms are defaults, not rules. Keep the long form when the short one hides a decision: a for loop with a try per row is clearer than a comprehension that needs a helper function and a walrus, and a plain if/else beats Counter when there are two keys. Match the surrounding code, the team's lint configuration and the Python versions you support before importing a pattern from a tutorial.

Version support is a real constraint. zip(strict=True) and isinstance(x, int | float) need Python 3.10, datetime.UTC needs 3.11, and Python 3.10 itself reached end of life in October 2026, according to the Python Developer's Guide. Check requires-python before you adopt a newer idiom, and set the linter's target-version to match it.

Idiomatic is not always faster either. On Python 3.15.2, a key that was always present cost 19.6 ms per million lookups with try/except KeyError against 35.5 ms with if key in d, but a key that was always missing cost 116.1 ms against 19.6 ms, because raising and catching KeyError costs more than a failed in test. Python 3.11.18 showed the same shape: 22.1 against 34.5 ms, and 136.5 against 24.4 ms. Each figure is the best of seven timeit runs of one million lookups on one shared Linux machine, so treat the ratios as indicative. Use EAFP when failure is rare; when it is routine, ask first.

Unrust's guide to idiomatic code (/guides/idiomatic-code) makes the same point across JavaScript, Python and TypeScript: idiomatic code is not always shorter, and the local codebase's conventions still decide what counts.

import timeit

setup = "d = {'a': 1}"
check = """
if KEY in d:
    v = d[KEY]
else:
    v = 0
"""
attempt = """
try:
    v = d[KEY]
except KeyError:
    v = 0
"""

for label, stmt in [("check first", check), ("try/except", attempt)]:
    for state, key in [("present", "'a'"), ("missing", "'z'")]:
        runs = timeit.repeat(stmt.replace("KEY", key), setup, number=1_000_000, repeat=7)
        print(f"{label}, key {state}: {min(runs) * 1000:.1f} ms")

# Python 3.15.2
# check first, key present: 35.5 ms
# check first, key missing: 19.6 ms
# try/except, key present: 19.6 ms
# try/except, key missing: 116.1 ms

# Python 3.11.18
# check first, key present: 34.5 ms
# check first, key missing: 24.4 ms
# try/except, key present: 22.1 ms
# try/except, key missing: 136.5 ms

Practise reading Python for idiom

Reading for idiom is a skill you can practise: look at a snippet, predict what it prints, then decide whether you would change it. Unrust's free diagnostic samples Idiom / Quality as one of six skills, alongside recall, tracing, find the flaw, debugging and AI-slop detection, and you can take it in Python. It takes about 14 minutes with the AI off, and with a free account you also get one practice queue a day.

For untimed practice, Unrust's Python idiomatic code page (/languages/python/idiomatic-code) pairs one original enumerate example with a checked result, a three-question checklist and a three-step practice loop. The Python AI-review page (/languages/python/reviewing-ai-generated-code) covers broad except blocks, default arguments, in-place methods and package calls in generated code.

Idiomatic Python: FAQ

What does idiomatic Python mean, and how is it different from Pythonic? In practice they mean the same thing. Idiomatic is the general word for code that follows a language's common idioms, and Pythonic is the Python community's word for it: the glossary defines it as code that closely follows the most common idioms of Python rather than concepts common to other languages. Neither means shortest, and both depend on the codebase you are working in.

What is the difference between Pythonic and non-Pythonic code? Non-Pythonic code carries over habits from another language: counting with range(len(x)), comparing with == None, joining strings with +=, or checking before every operation. Pythonic code uses the construct Python provides for the job. The glossary's own example is for i in range(len(food)) against for piece in food, and the tells table above lists six shapes to look for in a diff.

What are the most common Python idioms? Looping over items with enumerate and zip, unpacking and swapping, truth-value tests with is None, Counter and defaultdict, EAFP error handling with try and except, any and all over generators, join and f-strings, isinstance, and key= arguments. The ten sections above run each one, and list comprehensions have their own post (/blog/python-list-comprehensions).

What is idiomatic error handling in Python, EAFP or checking first? EAFP: try the operation and catch the specific exception, with only the call that can fail inside try and the rest in else. Check first when the check is cheap and failure is routine; in the timing above, a missing key cost about six times more with try/except than with in on Python 3.15.2. Never use a bare except:, which also catches KeyboardInterrupt.

Is idiomatic Python always shorter or faster, and when should you not use the idiom? No. any() with brackets builds the whole list first, and try/except costs more than a check when failures are common. Use an idiom when it makes the intent clearer to the next reader, and keep the long form when the short one hides a rule, when the project supports a Python version that lacks the idiom, or when the team's lint rules say otherwise.

References and next steps

Read Python for idiom against the clock

Take Unrust's free diagnostic in Python with the AI off: about 14 minutes. Idiom / Quality is one of six skills it samples, alongside recall, tracing, find the flaw, debugging and AI-slop detection.

More from the blog