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 filterif (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.
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/elsefor 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.