Warming up the neural circuits...
By the end of this chapter you will:
Comprehensions turned three-line loops into one readable line. They're the most idiomatic syntax in Python — once you learn them, you'll see them everywhere. But they have limits: complex logic, side effects, and deep nesting make them unreadable. Learn when to use them, and when to stick with a loop.
# Transform: map equivalent
numbers = [1, 2, 3, 4, 5]
doubled = [n * 2 for n in numbers]
# [2, 4, 6, 8, 10]
# Filter: filter equivalent
evens = [n for n in numbers if n % 2 == 0]
# [2, 4]
# Combined: filter then transform
names = ["Alice", "Bob", "Charlie", "Dave"]
short_upper = [n.upper() for n in names if len(n) <= 3]
# ['BOB']
# Real-world: extract prices
products = [{"name": "Apple", "price": 1.50}, {"name": "Banana", "price": 0.75}]
prices = [p["price"] for p in products]
# [1.50, 0.75]| Pattern | Syntax | Use when |
|---|---|---|
| Transform | [expr for x in list] | Apply function to each item |
| Filter | [x for x in list if cond] | Keep matching items |
| Filter+Transform | [expr for x in list if cond] | Transform matching items |
# Build dict from list
names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# Invert a dict
original
# Unique lengths
words = ["hello", "world", "hi", "python"]
lengths = {len(w) for w in words}
# {2, 5, 6}
# Unique first letters
# Conditional expression inside comprehension
numbers = [1, 2, 3, 4, 5]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
# ['odd', 'even', 'odd', 'even', 'odd']
#
# BAD: too complex
result = [func(x) for x in data if x > 0 and x < 100 and x % 2 == 0]
# GOOD: use a loop
result = []
for x in data:
if
[expression for item in iterable if condition]
↑ ↑ ↑ ↑
What Variable Source Filter
to create name data (optional)| Mistake | Why it's wrong | Fix |
|---|---|---|
[print(x) for x in range(5)] | Side effects in comprehension, builds useless list of Nones | Use a for loop |
[x for x in data if cond1 if cond2] | Two filters (confusing) | [x for x in data if cond1 and cond2] |
[[0]*3]*3 for 2D list | All rows are same object | [[0]*3 for _ in range(3)] |
| Comprehension with 3+ conditions | Unreadable | Use a for loop |
{"apple": 5, "banana": 6, "cherry": 6}[print(x) for x in range(5)] bad? What should you use instead?Beginner:
"What's the difference between a list comprehension and a for loop?"
A list comprehension is a concise way to create a new list from an iterable. It's more readable for simple transforms and filters. A for loop is more flexible — it can handle complex logic, side effects, and multi-step operations.
"When should you NOT use a comprehension?"
When the logic is complex (multiple conditions, nested loops), when you have side effects (printing, writing files), or when readability suffers. If the comprehension takes more than one line, use a loop.
Senior:
"What's the difference between a list comprehension and a generator expression?"
A list comprehension creates the entire list in memory:
[x*2 for x in range(1000000)]. A generator expression yields items one at a time:(x*2 for x in range(1000000)). Generators are memory-efficient for large datasets — they compute values on demand.
"Why is [[0]*3]*3 dangerous for creating 2D lists?"
All three rows reference the same list object. Modifying one row modifies all rows. Use
[[0]*3 for _ in range(3)]to create independent rows.
[expr for x in list] — transform[x for x in list if cond] — keep matching{k: v for k, v in d.items()}{expr for x in list}[x if cond else y for x in list](expr for x in list) — lazy, memory-efficientI want to…
├── Transform list → [expr for x in list]
├── Filter list → [x for x in list if cond]
├── Build dict → {k: v for k, v in items}
├── Build set → {expr for x in list}
├── Conditional → [x if cond else y for x in list]
└── Lazy eval → (expr for x in list)What does [x*2 for x in range(5)] create?
Key: The conditional expression goes BEFORE for, the filter goes AFTER for.
Rule: If the comprehension takes more than one line or has more than one condition, use a loop.