Comprehensions kyun exist karte hain: Loop boilerplate intent ko obscure kar deta hai. Compare karo:
# Verbose loopsquares = []for x in range(10): squares.append(x**2)# Comprehension: intent clear in one linesquares = [x**2 for x in range(10)]
Doosra version declarative hai—tum state karte ho kya chahiye (squared numbers) bina kaise ke (list initialize karo, loop mein append karo). Python ka parser bhi comprehensions ko manual loops se behtar optimize kar sakta hai.
Generators kyun: Ek list [x**2 for x in range(10**9)] 1 billion integers ke liye space allocate karta hai (~4-8 GB). Ek generator (x**2 for x in range(10**9)) iterator object ke liye ~200 bytes allocate karta hai. Values on the fly compute hoti hain.
Maano Tc = ek item compute karne ka time, n = items ki sankhya, k = collection par iterations ki sankhya.
List: Cost = n⋅Tc (upfront) + O(1) per access × k passes → (n⋅Tc+n⋅k)
Generator: Cost = Tc per access × n items × k passes → (n⋅Tc⋅k)
Agar k=1, generator jeet jaata hai (k ka factor chhota). Agar k>1 aur n chhota hai, list jeet jaati hai (recomputation bachao).
Recall Ek 12-saal ke bachche ko explain karo
Socho tumhare paas ek toy factory hai. Ek list comprehension aise hai jaise pehle saare toys banao, phir shelf par rakh do. Tum koi bhi toy kabhi bhi le sakte ho, lekin tumhe ek badi shelf chahiye.
Ek generator aise hai jaise tumhare paas ek magic box ho. Jab tum poochho "mujhe ek toy do," woh tab wahi ek toy banata hai aur tumhe deta hai. Agar aur chahiye, tum phir poochho aur woh agla banata hai. Box chhota hai, lekin tum peeche nahi ja sakte—ek baar toy lene ke baad, woh box se chala gaya.
Dict comprehension aise hai jaise phone book banana: tum names (keys) aur phone numbers (values) ek hi step mein pair kar lete ho, ek ek likhne ki jagah.
10 toys wale homework problems ke liye, sab bana lo (list). Santa ki workshop ke liye jo ek billion toys bana rahi hai, magic box use karo (generator)—ek billion toys shelf par kabhi fit nahi honge!
1.4.01-Basic-Python-syntaxand-data-structures — comprehensions lists, dicts, sets par build karte hain
1.4.02-NumPy-arrays-and-vectorization — NumPy ka apna "vectorized" iteration hai (broadcasting) jo numeric data ke liye comprehensions se faster hai
1.4.04-File-IO-and-data-loading — large CSV/JSON files stream karne ke liye generators crucial hain
1.5.01-Batch-processing-and-mini-batches — ML data loaders generators use karte hain batches lazily yield karne ke liye
2.3.02-Iterator-protocol — generators under the hood iterator protocol implement karte hain
#flashcards/ai-ml
List comprehension kya hai? :: Ek syntactic construct [expr for item in iterable if condition] jo har item par expression apply karke list banata hai, optionally filtering ke saath. Explicit for-loop-append patterns ko ek declarative one-liner se replace karta hai.
Generator kya hai?
Ek function jo yield use karta hai ya ek expression (expr for ...) jo values lazily produce karta hai (ek ek karke, on demand) memory mein saari values store karne ki jagah. Sequence ki length chahe kuch bhi ho, O(1) memory use karta hai.
List comprehension ki jagah generator kyun use karein?
Jab large datasets ke saath kaam karo aur sirf ek pass chahiye—generators constant memory use karte hain (sirf iterator state) saare items ke liye space allocate karne ki jagah. Tradeoff: generator ko reuse ya index nahi kar sakte.
Generator function mein yield kya karta hai?
Execution pause karta hai, caller ko ek value return karta hai, aur function ki state save karta hai. Jab agla value request hota hai, execution yield ke bilkul baad resume hoti hai. Saare results store kiye bina stateful iteration enable karta hai.
[x**2 for x in range(10**9)] ki memory cost kya hai?
Approximately 4-8 GB (1 billion integers × ~28 bytes per Python int object). Ek generator (x**2 for x in range(10**9)) ~200 bytes cost karta hai (sirf iterator overhead).
Comprehension se nested list ko flatten kaise karte hain?
[item for row in matrix for item in row]. Left-to-right nested loops ki tarah padho: outer for row in matrix, phir inner for item in row. Har item result mein append hota hai.
Kya generator ko kai baar iterate kar sakte hain?
Nahi. Generators ek iteration ke baad consumed ho jaate hain. list(gen) do baar call karne par pehli baar values milti hain, phir doosri baar empty list milti hai (generator exhausted ho jaata hai).
List comprehension generator se faster kab hoti hai?
Jab tumhe data par multiple passes chahiye aur dataset memory mein fit ho jaaye. List computation cost ek baar upfront pay karta hai; generator har access par recompute karta hai. n items par k passes ke liye, list cost n⋅Tc+n⋅k hai vs generator n⋅Tc⋅k.
Dict comprehension ka syntax kya hai?
{key_expr: value_expr for item in iterable if condition}. Example: {x: x**2 for x in range(5)} produce karta hai {0:0, 1:1, 2:4, 3:9, 4:16}.