Python List Comprehensions — 5 Patterns You'll Actually Use
0views
C
CelesteAI
Description
A list comprehension is a one-line for loop that builds a list. Same algorithm, fewer characters, and faster because the loop runs in C instead of Python bytecode. This tutorial walks the five patterns you'll meet in real code, on a tiny numeric example, plus the one case where a regular for loop is still the right call.
The five patterns: map (transform each element), filter (keep elements that pass), map and filter combined, flatten (nested for-clauses), and dict and set comprehensions (same syntax, different brackets). Then a timing comparison on 100,000 items showing the comprehension runs roughly twice as fast as the equivalent for-plus-append loop. And finally, the rule for when NOT to reach for a comprehension — anywhere the body needs multiple statements, side effects, or a break or continue.
What You'll Build:
- list_comp.py — one file, five numbered comprehension patterns, a 100k-item speed comparison, and a deliberate for-loop counterexample for the case where comprehension stops being the right tool.
- Pattern 1: map — [x * x for x in nums]. Transform each element. The for+append equivalent is four lines; the comprehension is one.
- Pattern 2: filter — [x for x in nums if x % 2 == 0]. Keep elements matching a condition. The if clause goes at the end.
- Pattern 3: map and filter combined — [x * x for x in nums if x gt 3]. Same shape, both clauses in one expression.
- Pattern 4: flatten — [item for row in matrix for item in row]. Multiple for clauses read left-to-right like nested for loops. The outer for goes first, the inner second.
- Pattern 5: dict and set comprehensions — {w: len(w) for w in words} and {x % 3 for x in range(100)}. Same syntax, curly braces. With a colon you get a dict; without, you get a set.
- Speed — the comprehension version of a 100,000-item loop runs about 2x faster than the equivalent for-plus-append. Same work, less Python-level overhead, more of the loop runs in C under the hood.
- When NOT to use a comprehension — when the body needs multiple statements, when you need break/continue, when side effects (logging, file writes) matter more than the result. Reach for a regular for loop. Don't try to cram everything into a single expression.
Timestamps:
0:00 - Intro — list comprehension in one minute
0:22 - Preview — five patterns, one speedup, one counterexample
1:07 - Open list_comp.py in nvim
1:22 - Pattern 1 — map
1:42 - Pattern 2 — filter
2:00 - Pattern 3 — map + filter
2:18 - Pattern 4 — flatten
2:42 - Pattern 5 — dict + set
3:08 - Timing — 2x faster than for+append
3:35 - When to use a for loop instead
4:00 - Save and run
4:10 - End screen — recap
Key Takeaways:
1. A list comprehension is a one-line for loop that builds a list. The result-expression goes first, the iteration second, and an optional filter clause goes at the end. Same algorithm as for-plus-append, less code, and roughly twice as fast because more of the loop runs in C under the hood instead of Python bytecode.
2. The five patterns cover almost every real use. Map ([x*x for x in nums]), filter ([x for x in nums if cond]), map-plus-filter ([x*x for x in nums if cond]), flatten ([item for row in matrix for item in row]), and dict-or-set comprehensions ({w: len(w) for w in words}). Memorize the shape — you'll see it everywhere in modern Python.
3. Comprehensions are faster than for-plus-append on the same job. On 100,000 items the comprehension runs about 2x faster. The reason is that the result list is allocated in one go and the loop body executes inside CPython's evaluation loop without the per-iteration overhead of a Python-level .append method call. Same complexity, less constant factor.
4. The order of multiple for clauses reads left to right, like nested for loops. [item for row in matrix for item in row] is the same as for row in matrix: for item in row: yield item. The outer loop variable becomes available to the inner loop's expressions. Get this backwards and the comprehension throws NameError.
5. When the body needs more than one expression — when you need break, continue, multiple statements, logging, or any side effect — switch to a regular for loop. Don't try to cram everything into one comprehension. The point of the comprehension is readability when the transformation is simple; cramming makes it less readable, not more.
📺 Deeper dive: Common Questions Ep 9 (iterrows vs vectorize) measures the same Python-loop-overhead pattern on pandas DataFrames. https://www.youtube.com/watch?v=-v5SU8bZfDA
This channel is run by Claude AI. Tutorials AI-produced; reviewed and published by Codegiz. Source code at codegiz.com.
#Python #ListComprehension #PythonTutorial #LearnPython #PythonPerformance #PythonBasics #PythonTips
---
Generated by Claude AI · part of the Common Questions in Python series