1.2.34Introduction to Programming (Python)

List comprehensions — `[expr for x in iterable if condition]`

1,897 words9 min readdifficulty · medium6 backlinks

WHY does this feature exist?


WHAT is the exact anatomy?

The four moving parts, in reading order vs execution order:

Part Name Role
expr output expression what goes INTO the new list (computed last per item)
for x in iterable the loop where items come from (runs first)
if condition filter (optional) keep x only if True

![[1.2.34-List-comprehensions-—-`[expr-for-x-in-iterable-if-condition]`.png]]


HOW to derive it from the loop (do this once, never memorise)


More worked examples



Flashcards

What is the general template of a list comprehension?
[expr for x in iterable if condition]
In execution order, which part runs first: expr, for, or if?
The for (pick x), then if (filter), then expr (compute). Reading order ≠ execution order.
Where does the filter if (no else) go in a comprehension?
After the for: [x for x in xs if cond].
Where does the conditional if/else (ternary) go?
Before the for, as part of expr: [a if cond else b for x in xs].
Rewrite [x**2 for x in range(4)] as a loop.
r=[]; for x in range(4): r.append(x**2)[0,1,4,9].
What does [c for row in grid for cell in row]-style multi-for mean?
Nested loops; leftmost for is the outermost loop, read top-to-bottom.
What is the value of [n for n in [-1,2,-3] if n>0]?
[2] (filters out negatives, keeps items unchanged).
Is the if condition part required?
No, it is optional; without it every item is included.

Recall Feynman: explain it to a 12-year-old

Imagine a conveyor belt of apples. A list comprehension is a tiny factory: the belt brings each apple (for apple in belt), a guard throws away the rotten ones (if apple is good), and a machine turns each remaining apple into apple juice (expr = juice). At the end you get a new box of apple juice. You didn't have to write "take empty box, walk to belt, check apple, drop juice in box" four times — you just described the factory in one sentence and Python built it for you.


Connections

  • For loops — the comprehension is sugar over a for loop.
  • Conditional expressions (ternary)a if cond else b used inside expr.
  • Dictionary and set comprehensions — same idea with {} instead of [].
  • Generator expressions(...) lazy version that doesn't build the whole list.
  • map() and filter() — functional equivalents of transform and filter.
  • range() and iterables — what feeds the for x in iterable slot.

Concept Map

collapses into

contains

contains

contains

supplies x

keeps x if True

appended to

written as

actually runs as

causes

fixes via loop rewrite

4-line for loop ritual

List comprehension one-liner

expr output

for x in iterable

if condition optional

New list

Reading order expr first

Execution order for-if-expr

Steel-man misread

Hinglish (regional understanding)

Intuition Hinglish mein samjho

List comprehension ek shortcut hai naya list banane ka. Normally tum empty list banate ho, phir for loop chalate ho, if se filter karte ho, aur append karte ho — 4 lines. Comprehension yeh sab ek line me kar deta hai: [expr for x in iterable if condition]. Padho aise: "har x ke liye jo iterable me hai, agar condition sach hai, toh expr daal do".

Sabse important baat: reading order aur execution order alag hai. Likha pehle expr jaata hai, par chalta pehle for hai — Python pehle x uthata hai, phir if se check karta hai, tabhi expr compute karta hai. Yaad rakhne ke liye loop ko mann me wapas khol lo: loop → filter → append.

Do tarah ke if hote hain, yahan log confuse hote hain. Filter if (bina else) for ke baad aata hai — yeh decide karta hai item rakhna hai ya nahi: [x for x in xs if x>0]. Ternary if/else for ke pehle aata hai (kyunki yeh expr ka part hai) — yeh decide karta hai kaunsi value daalni hai: [x if x>0 else 0 for x in xs]. Mnemonic: "Choose-before, Cut-after".

Kab use karein? Jab transform ya filter simple ho, tab comprehension clean aur fast hai (loop C me chalta hai). Lekin agar bahut saare nested if, ya print/side-effects ho, toh normal for loop hi behtar — code padhne layak rehna chahiye.

![[audio/1.2.34-List-comprehensions-—-`[expr-for-x-in-iterable-if-condition]`.mp3]]

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections