Lesson · Idiomatic Python & Code Quality
Pythonic Style
58 min readPythonic Style
Pythonic code uses the language's protocols and standard idioms to make intent obvious. Readability matters more than compressing the most behavior into the fewest characters.
Learning goals
- Explain why iterating a collection directly beats driving it with
range(len(...))in most loops. - Use
enumeratewhen the position matters andzipto walk parallel sequences, including thestrict=Trueguard. - Read and write comprehensions, and recognize the point where an explicit loop is clearer.
- Choose between EAFP and LBYL for a check against external state, and say when a pre-check can go stale.
- Decide when compact syntax has crossed into cleverness and restructure it for the next reader.
Mental model
The choices form a ladder: each step adds a tool only when the previous one stops expressing the intent. The moment a step makes the reader pause is the moment to climb back down.
Mental model
read it top to bottom
iterate the object directly (default) ↓ need the position too? enumerate(records, start=1) ↓ is the item compound? unpack into meaningful names (name, score) ↓ transforming the whole sequence? comprehension with a filter ([name for name, score in records if score >= 98])
Core idea
Pythonic style is choosing the protocol that matches the data flow: iteration replaces index arithmetic, unpacking names structure, comprehensions express filtered projections, and EAFP or LBYL depends on whether the check can go stale. Each choice trades a little cleverness for a lot of readable intent.
Prefer iteration over manual indexing when possible
Iterating the collection itself (for record in records) is clearer and usually faster than driving an index with range(len(records)). Reach for an explicit index only when the position carries meaning of its own, and use enumerate when you need the position and the item together.
Tuple unpacking
Tuple/iterable unpacking assigns structural parts directly to meaningful names and often removes manual indexing. Use a starred target when the middle length is variable.
enumerate
enumerate wraps an iterable and yields (index, item) pairs, so the loop no longer maintains a manual counter. start= sets the first index, and the result is a lazy iterator: consume it once, or wrap it in list() when you truly need all pairs at once.
zip
zip walks several iterables in parallel and yields a tuple of one element from each. It stops at the shortest input unless strict=True (Python 3.10 and later) turns a length mismatch into a ValueError. Like enumerate, it returns a lazy iterator.
Comprehensions
A comprehension builds a list, set, or dictionary in one expression: an output expression, a for clause, and optional if filters. It replaces the append-in-a-loop pattern, but more than one nested clause is usually where it stops being easier to read.
Context managers
Context managers make setup and cleanup visible in control flow. Prefer them for resources whose release must happen even when an exception interrupts the body.
EAFP vs LBYL
EAFP attempts the operation and catches an expected failure; LBYL checks a condition first. In concurrent or external-state scenarios, a pre-check can become stale before the operation executes.
Readability over cleverness
Python offers compact syntax, but maintainable code optimizes for the next reader. Prefer the simplest form that makes data flow, error behavior, and invariants obvious.
Walkthrough
enumerate(records, start=1)pairs each tuple with a human-readable position; changingstartchanges only the numbering, never the order of visits.- The loop unpacks in one line: first the pair
(position, record), then the record(name, score). Give a record the wrong shape and the unpacking raisesValueErrorat runtime. - The comprehension reads left to right as project (
name), source (for ... in records), filter (if score >= 98). Swapping clauses produces a syntax error rather than a wrong result, which is a useful way to remember the grammar. - Predict before running: what
start=1changes, whetherhigh_scoresholds names or tuples, and what happens when a record has three fields.
Experiments to try
- Delete
start=1and diff the output; then decide which form you would keep, and why the default is still the default. - Feed the loop a malformed record such as
("Ada",)and read theValueError; rewrite the unpacking so the failure is clearer or cannot happen. - Build two lists of different lengths and run
zip(first, second)and thenzip(first, second, strict=True); record the truncation versus the error. - Convert
high_scoresto an explicit loop withappendand back; stop at the form you would rather review in a pull request.
Common mistakes
- Reaching for
range(len(records))out of habit and indexing inside the loop when direct iteration says the same thing with less room for an off-by-one. - Keeping a manual counter beside the loop instead of giving
enumeratethe job it exists for. - Letting
ziptruncate silently: when the lengths differ, the shortest input wins unlessstrict=Trueis set. - Nesting comprehensions until the reading order is no longer left to right; the threshold is the first moment a reviewer has to pause.
Practice: Easy
- Write the index-style version of the loop first (
for i in range(len(records))), then rewrite it as direct iteration and asenumerate(records, start=1). Compare the three line by line and note what each version makes the reader track. - Pair two short lists with
zipand print each pair; then rerun with lists of different lengths and explain the output, usingstrict=Trueas the contrast. - Convert the
high_scorescomprehension into an explicit loop withappend, then convert it back. Record which version you read faster and why.
Practice: Medium
- Rewrite a validate-then-act function (LBYL) in EAFP form for a case where the check can go stale, such as a file that may disappear between the check and the
open(). State the failure mode each version has. - Take an index-heavy loop from your own code and rewrite it with
enumerateplus unpacking. Keep the behavior identical and list what disappeared: the counter, the indexing, or both. - Write a one-paragraph review rule for when a comprehension is acceptable and when an explicit loop wins, then test the rule against three pieces of code from this module.
Practice: Hard
- Refactor a small records-report program into three parts: loading and iteration, transformation (comprehension or generator), and formatting. Define the boundary of each part so it can be tested alone.
- Build a style failure lab that triggers at least two classic traps, such as mutating a list while iterating it,
ziptruncation withstrictoff, or a comprehension that hides an expensive call. Explain the mechanism behind each result. - Connect this lesson to the testing module: take one style refactor you made and describe how it changes the tests you would write for the same behavior.
Lesson checklist
- I can pick between direct iteration,
enumerate, unpacking, and a comprehension for a given data flow. - I can explain when a pre-check (LBYL) can go stale and EAFP is the safer choice.
- I can spot the moment compact syntax turns into cleverness and restructure it.
- I can read a nested comprehension left to right and say what each clause does.
Remember
Pythonic style is choosing the protocol that matches the data flow: iterate the object directly, reach for `enumerate` when the position matters, unpack compound items into meaningful names, and express filtered projections as comprehensions. Keep the readability bar concrete: if a reviewer has to pause to reconstruct your intent, the simpler form wins.
Interview angles
What is the main purpose of **Prefer iteration over manual indexing when possible**?+
Iterating the collection itself is clearer and usually faster than driving an index with range(len(records)). Reach for an explicit index only when the position carries meaning of its own, and use enumerate when you need the position and the item together.
What should you pay attention to when using **Tuple unpacking**?+
Tuple/iterable unpacking assigns structural parts directly to meaningful names and often removes manual indexing. Use a starred target when the middle length is variable.
How does **enumerate** fit into this lesson?+
enumerate wraps an iterable and yields (index, item) pairs, so the loop no longer maintains a manual counter. start= sets the first index, and the result is a lazy iterator: consume it once, or wrap it in list() when you truly need all pairs at once.
When does `zip` silently hide a bug, and what prevents it?+
zip stops at the shortest input, so lists of different lengths lose data without an error; strict=True (Python 3.10 and later) turns that length mismatch into a ValueError instead.