Exercises — List comprehensions — `[expr for x in iterable if condition]`
1.2.34 · D4· Coding › Introduction to Programming (Python) › [[1.2.34 List comprehensions — `[expr for x in iterable if condition]`|List comprehensions — `[expr for x in iterable if condition]]]
Neeche, ek picture "conveyor belt" mental model dikhati hai jise hum baar baar reuse karte hain — items left se flow karte hain, filter kuch ko drop karta hai, transform survivors ko reshape karke ek naya list banata hai.
![Figure — List comprehensions — `[expr for x in iterable if condition]`](/notes-assets/img/42b383a8a0218fe8.webp)
Level 1 — Recognition
Tumhe sirf template padhni hai aur chaar slots match karne hain:
expr, for x in iterable, aur optional if condition.
L1.1
Recall Solution L1.1
expr=w.upper()— jo naye list mein jaata hai.iterable=["hi", "yo"]— jahan se harwaata hai.condition=len(w) == 2—wko tabhi rakho jab yehTrueho.
Dono words ki length 2 hai, isliye dono survive karte hain → ["HI", "YO"].
L1.2
Recall Solution L1.2
Koi if nahi, isliye har item rakha jaata hai. Hum har ek mein 1 add karte hain:
Answer: [11, 21, 31].
L1.3
Recall Solution L1.3
Yahan expr sirf n hai, isliye survivors unchanged pass hote hain. Test n > 5 7 aur
9 ko rakhta hai, 4 aur 2 ko drop karta hai.
Answer: [7, 9].
Level 2 — Application
Ab tum ek comprehension ya uska exact output produce karte ho, sign/edge behaviour ke saath.
L2.1
Recall Solution L2.1
Odd ka matlab x % 2 == 1 (2 se divide karne ke baad remainder 1 ho).
[x**2 for x in range(6) if x % 2 == 1]range(6) hai 0,1,2,3,4,5. Odds hain 1, 3, 5:
Answer: [1, 9, 25].
L2.2
Recall Solution L2.2
Hum items drop nahi kar rahe, balki ek value choose kar rahe hain, isliye hum conditional expression
(a if cond else b) use karte hain jo for ke pehle aata hai:
[n if n >= 0 else 0 for n in [3, -1, -4, 5]]- →
3rakho - ? Nahi →
0 - ? Nahi →
0 - →
5rakho
Answer: [3, 0, 0, 5]. (Dekho Conditional expressions (ternary).)
L2.3
Recall Solution L2.3
(a) Iterable empty hai, isliye loop body kabhi nahi chalta → [].
(b) Paanch items consider hote hain, koi bhi x > 100 pass nahi karta, isliye sab filter out ho jaate hain → [].
(c) range(0) koi number produce nahi karta → [].
Lesson: ek empty result do alag tareekon se hota hai — ek empty source, ya ek filter jo sab kuch reject kar de. Dono legal hain, dono error nahi hain.
Level 3 — Analysis
Tumhe nested logic trace karni hai aur ordering aur quantity ke baare mein sochna hai.
L3.1
Recall Solution L3.1
Do fors outer-to-inner, top-to-bottom padte hain — bilkul nested loops ki tarah:
for row in grid: # outer (leftmost for)
for cell in row: # inner
result.append(cell)Row by row: [1,2,3] → 1,2,3; [4] → 4; [] → (kuch nahi); [5,6] → 5,6.
Answer: [1, 2, 3, 4, 5, 6], jisme 6 elements hain. Empty inner list kuch contribute nahi karta —
bilkul waisa jaise ek empty list par inner loop zero times chalta hai.
L3.2
Recall Solution L3.2
Outer i 0,1,2 chalta hai; har ek ke liye, inner j 0,1,2 chalta hai; sirf wahi pairs rakho jahan i < j.
i=0:j=1→(0,1),j=2→(0,2) (j=0 fail karta hai 0<0)i=1:j=2→(1,2) (j=0,1 fail)i=2: koij2 < jsatisfy nahi karta
Answer: [(0, 1), (0, 2), (1, 2)] — exactly 3 "strictly increasing" pairs.
L3.3
Recall Solution L3.3
Execution order ke hisaab se inner for y in range(x) y ko bind karta hai filter if y > 0 ke
pehle, isliye y hamesha defined hota hai jab test hota hai. Trace karo:
x=0:range(0)empty hai → koiynahi.x=1:range(1)=0→y=0,0 > 0False → drop.x=2:range(2)=0,1→y=0dropped,y=1kept.
Answer: [1]. Rule yeh hai: ek filter if koi bhi variable use kar sakta hai jo uske left ke kisi for ne already bind kiya ho.
Level 4 — Synthesis
Transform + filter + nesting combine karo, aur sahi tool choose karo.
L4.1
Recall Solution L4.1
"3 se divisible" ka matlab x % 3 == 0. "Cube" ka matlab x**3.
[x**3 for x in range(1, 11) if x % 3 == 0]range(1, 11) = 1..10; 3 ke multiples hain 3, 6, 9:
Answer: [27, 216, 729].
L4.2
Recall Solution L4.2
Do ifs saath kaam karte hain — filter if (for ke baad) odds drop karta hai; ternary (for se pehle) label pick karta hai:
["big" if n > 4 else "small" for n in [-5, -2, 0, 3, 8] if n % 2 == 0]Evens hain -2, 0, 8 (note: -5 % 2 == 1, 3 % 2 == 1, isliye dono odd → dropped).
-2 > 4? Nahi →"small"0 > 4? Nahi →"small"8 > 4? Haan →"big"
Answer: ["small", "small", "big"].
L4.3
Recall Solution L4.3
Comprehension (ek English sentence):
[len(w) for w in ["cat", "dog", "banana", "sky"] if "a" in w]"a" wale words: "cat" (3), "banana" (6). → [3, 6].
Functional equivalent:
list(map(len, filter(lambda w: "a" in w, ["cat","dog","banana","sky"])))Same result [3, 6], lekin comprehension left-to-right padhta hai jaise "mujhe length do har
word ki agar usme 'a' ho" — map(filter(...)) ko inside-out nest karne se zyada clear. Yahan comprehension prefer karo.
Level 5 — Mastery
Kuch aisa banao jo ek real program use kare; equivalence aur laziness ke baare mein sochо.
L5.1
Recall Solution L5.1
Main diagonal hai (0,0), (1,1), (2,2). Hum do fors nest karte hain aur r != c se unhe filter out karte hain:
[(r, c) for r in range(3) for c in range(3) if r != c]Saare 9 pairs minus 3 diagonal wale = 6 pairs:
[(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)].
Sanity count: — list length se match karta hai.
L5.2
Recall Solution L5.2
(a) A ek list hai — saare 1000 squares turant build aur store ho jaate hain.
(b) B ek generator hai (dekho Generator expressions) — yeh ek recipe store karta hai, squares ek ek karke,
demand par produce karta hai, almost koi memory use nahi karta.
(c) . Toh sum(B) = 332833500.
(d) Ek generator ek full pass ke baad exhausted ho jaata hai. Doosra sum(B) kuch nahi dekhta →
0. (Ek list A baar baar sum kiya ja sakta hai; ek generator nahi.)
L5.3
Recall Solution L5.3
Comprehension trace (for → if → expr):
x=0: even → append0x=1: odd → skipx=2: even → append20x=3: odd → skip
→ [0, 20].
Loop jisme yeh desugar hota hai:
r = []
for x in range(4):
if x % 2 == 0:
r.append(x * 10)
# r == [0, 20]Identical output [0, 20]. Yahi defining law hai: comprehension us loop ke liye pure syntactic
sugar hai — same picks, same filter, same appends, same list.
Recall Ek-line self-test recap
Filter if ki position ::: for ke baad (koi else nahi) — decide karta hai ki include karna hai ya nahi.
Ternary if/else ki position ::: for se pehle, expr ke andar — decide karta hai kya value.
Nested for order ::: sabse left wala for sabse outer loop hai, top-to-bottom padho.
Empty result ke do tarike ::: empty source iterable, ya ek filter jo sab kuch reject kar de.
Generator jo full consumption ke baad reuse ho ::: kuch yield nahi karta — woh exhausted hai.
Connections
- For loops — upar har solution mein equivalent loop dikhaya gaya hai.
- Conditional expressions (ternary) —
forse pehle wala value chooser (L2.2, L4.2). - Dictionary and set comprehensions —
{}ke saath same slot logic. - Generator expressions — lazy
(...)version (L5.2). - map() and filter() — functional equivalents (L4.3).
- range() and iterables — poore
for x in iterableslot ko feed karta hai.