Python Comprehensions का complete guide – list comprehension, dictionary comprehension, set comprehension, generator expressions, nested comprehensions, conditional filtering, और performance comparison with Hindi explanations।
Introduction (परिचय)
Comprehensions Python का एक elegant feature है जो loops और conditionals को एक concise, readable expression में combine करता है।
4 Types of Comprehensions: - 📋 List Comprehension → [expr for item in iterable if cond] - 📖 Dict Comprehension → {k: v for item in iterable if cond} - 🔵 Set Comprehension → {expr for item in iterable if cond} - ⚙️ Generator Expression → (expr for item in iterable if cond)
2. Conditional List Comprehension
Filter Only (if condition)
nums = list(range(1, 21))
# Even numbers only
evens = [x for x in nums if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Odd numbers
odds = [x for x in nums if x % 2 != 0]
print(odds) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Numbers divisible by 3 and 5
fizzbuzz = [x for x in nums if x % 3 == 0 and x % 5 == 0]
print(fizzbuzz) # [15]
# Multiples of 3 or 5
mult = [x for x in nums if x % 3 == 0 or x % 5 == 0]
print(mult) # [3, 5, 6, 9, 10, 12, 15, 18, 20]
# Filter positive numbers
mixed = [-5, -3, -1, 0, 1, 3, 5, -2, 4]
positives = [x for x in mixed if x > 0]
print(positives) # [1, 3, 5, 4]
# Filter strings by length
words = ["hi", "hello", "python", "a", "programming", "go"]
long_words = [w for w in words if len(w) > 4]
print(long_words) # ['hello', 'python', 'programming']
# Filter and transform
scores = {"Alice": 85, "Bob": 72, "Charlie": 91, "Dave": 68, "Eve": 78}
passed = [name for name, score in scores.items() if score >= 75]
print(passed) # ['Alice', 'Charlie', 'Eve']
# if-else goes BEFORE for (expression part)
nums = list(range(1, 11))
# Label even/odd
labels = ["even" if x % 2 == 0 else "odd" for x in nums]
print(labels)
# ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
# Absolute values
mixed = [-3, -1, 0, 2, -5, 4]
abs_vals = [x if x >= 0 else -x for x in mixed]
print(abs_vals) # [3, 1, 0, 2, 5, 4]
# FizzBuzz
fb = ["FizzBuzz" if x%15==0 else "Fizz" if x%3==0 else "Buzz" if x%5==0 else str(x)
for x in range(1, 16)]
print(fb)
# ['1','2','Fizz','4','Buzz','Fizz','7','8','Fizz','Buzz','11','Fizz','13','14','FizzBuzz']
# Replace negative with 0 (clamp)
values = [5, -3, 8, -1, 10, -7, 2]
clamped = [max(0, v) for v in values]
print(clamped) # [5, 0, 8, 0, 10, 0, 2]
# ⚠️ Note: if-else BEFORE for, filter-only if AFTER for
# [expr if cond else expr2 for x in it] → transform
# [expr for x in it if cond] → filter
3. Nested List Comprehension
# 2D matrix – nested comprehension
# Outer loop first, inner loop second
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# Equivalent loop:
result = []
for i in range(1, 4):
row = []
for j in range(1, 4):
row.append(i * j)
result.append(row)
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [val for row in matrix for val in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Note: for loops are in same order as nested loops
# [val for row in matrix for val in row]
# ↕ ↕ ↕
# expr outer loop inner loop
# Multiplication table
table = [[f"{i}×{j}={i*j}" for j in range(1, 4)] for i in range(1, 4)]
for row in table:
print(", ".join(row))
# 1×1=1, 1×2=2, 1×3=3
# 2×1=2, 2×2=4, 2×3=6
# 3×1=3, 3×2=6, 3×3=9
# Cartesian product
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
products = [(c, s) for c in colors for s in sizes]
print(products)
# [('red','S'), ('red','M'), ('red','L'), ('blue','S'), ('blue','M'), ('blue','L')]
# Filter in nested
matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]
positives = [val for row in matrix for val in row if val > 0]
print(positives) # [1, 3, 5, 7, 9]
# Transpose matrix
original = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in original] for i in range(3)]
print(transposed)
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
4. Dictionary Comprehension
# Basic: {key_expr: val_expr for item in iterable}
# Squares dict
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# String to index mapping
words = ["apple", "banana", "cherry"]
word_idx = {word: i for i, word in enumerate(words)}
print(word_idx) # {'apple': 0, 'banana': 1, 'cherry': 2}
# Invert a dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# Filter dict by value
scores = {"Alice": 85, "Bob": 72, "Charlie": 91, "Dave": 68}
passed = {k: v for k, v in scores.items() if v >= 75}
print(passed) # {'Alice': 85, 'Charlie': 91}
# Transform values
prices = {"apple": 100, "banana": 50, "cherry": 200}
discounted = {k: v * 0.9 for k, v in prices.items()}
print(discounted) # {'apple': 90.0, 'banana': 45.0, 'cherry': 180.0}
# From two lists
keys = ["name", "age", "city"]
vals = ["Alice", 25, "Delhi"]
profile = {k: v for k, v in zip(keys, vals)}
print(profile) # {'name': 'Alice', 'age': 25, 'city': 'Delhi'}
# Conditional transformation
nums = range(1, 11)
classify = {x: ("even" if x%2==0 else "odd") for x in nums}
print(classify)
# {1: 'odd', 2: 'even', 3: 'odd', ...}
# Nested dict comprehension
matrix = {f"row{i}": {f"col{j}": i*j for j in range(1,4)} for i in range(1,4)}
print(matrix["row2"]["col3"]) # 6
5. Set Comprehension
# Basic: {expr for item in iterable if condition}
# Squares set (no duplicates)
squares = {x**2 for x in range(-5, 6)}
print(sorted(squares)) # [0, 1, 4, 9, 16, 25]
# Unique first letters
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
first_letters = {w[0] for w in words}
print(sorted(first_letters)) # ['a', 'b', 'c']
# Unique lengths
lengths = {len(w) for w in words}
print(sorted(lengths)) # [5, 6, 8, 9, 10]
# Filter + unique
nums = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique_evens = {x for x in nums if x % 2 == 0}
print(unique_evens) # {2, 4}
# Common chars in two strings
s1 = set("programming")
s2 = set("algorithm")
common = {c for c in s1 if c in s2}
print(sorted(common)) # ['a', 'g', 'i', 'm', 'r']
# Or simply: s1 & s2
# Vowels in a sentence
sentence = "Hello World Python"
vowels = {c.lower() for c in sentence if c.lower() in "aeiou"}
print(sorted(vowels)) # ['e', 'o']
6. Generator Expressions
Generators lazy होते हैं – values on-demand produce होती हैं, memory में store नहीं होतीं।
# Syntax same as list comprehension but with () instead of []
# List comprehension – all values in memory immediately
list_comp = [x**2 for x in range(10)]
print(type(list_comp)) # <class 'list'>
print(list_comp) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Generator expression – lazy, one at a time
gen_exp = (x**2 for x in range(10))
print(type(gen_exp)) # <class 'generator'>
print(gen_exp) # <generator object ...>
# Get values from generator
print(next(gen_exp)) # 0
print(next(gen_exp)) # 1
print(next(gen_exp)) # 4
# Convert to list when needed
print(list(gen_exp)) # [9, 16, 25, 36, 49, 64, 81] (remaining)
# Use directly in functions (no extra brackets needed)
nums = range(1, 1000001)
# sum() with generator (memory efficient!)
total = sum(x**2 for x in nums)
print(total) # 333333833333500000
# max() with generator
largest = max(x**2 for x in range(1, 11))
print(largest) # 100
# any(), all() with generators (short-circuits!)
has_negative = any(x < 0 for x in [1, 2, 3, -1, 4])
print(has_negative) # True (stops at -1)
all_positive = all(x > 0 for x in [1, 2, 3, 4, 5])
print(all_positive) # True
Memory Comparison
import sys
# List comprehension – all in memory
list_c = [x**2 for x in range(1000)]
gen_e = (x**2 for x in range(1000))
print(f"List: {sys.getsizeof(list_c):,} bytes") # ~8,056 bytes
print(f"Gen: {sys.getsizeof(gen_e):,} bytes") # ~104 bytes
# For million items
list_big = [x for x in range(1_000_000)]
gen_big = (x for x in range(1_000_000))
print(f"Big List: {sys.getsizeof(list_big):,} bytes") # ~8,000,056 bytes
print(f"Big Gen: {sys.getsizeof(gen_big):,} bytes") # ~104 bytes (constant!)
When to use Generator vs List:
| Use Generator when... | Use List when... |
|---|
| Large data, memory tight | Small data, random access needed |
| Only iterate once | Multiple iterations needed |
| Early termination possible | All values needed at once |
| Piping to other functions | Indexing required (gen[5] ❌) |
7. Walrus Operator in Comprehensions (Python 3.8+)
:= (walrus/assignment expression) – comprehension में compute और filter करना।
# Without walrus – compute twice
results = [heavy_compute(x) for x in data if heavy_compute(x) > 10] # ❌ double compute
# With walrus – compute once
results = [y for x in data if (y := heavy_compute(x)) > 10] # ✅ single compute
# Practical example
import math
nums = [4, -1, 9, 0, 16, -5, 25]
# Compute sqrt only for positive numbers, filter results > 2
filtered = [root for x in nums if x > 0 and (root := math.sqrt(x)) > 2]
print(filtered) # [3.0, 4.0, 5.0]
# Process strings: filter and store result
texts = [" hello ", "", " ", "world", " python "]
cleaned = [s for t in texts if (s := t.strip())] # strip and filter empty
print(cleaned) # ['hello', 'world', 'python']
import timeit
# Test: create list of squares 1 to 1000
# Method 1: for loop
def using_loop():
result = []
for x in range(1, 1001):
result.append(x**2)
return result
# Method 2: list comprehension
def using_comprehension():
return [x**2 for x in range(1, 1001)]
# Method 3: map()
def using_map():
return list(map(lambda x: x**2, range(1, 1001)))
# Benchmark
t1 = timeit.timeit(using_loop, number=10000)
t2 = timeit.timeit(using_comprehension, number=10000)
t3 = timeit.timeit(using_map, number=10000)
print(f"Loop: {t1:.4f}s")
print(f"Comprehension: {t2:.4f}s") # ← typically fastest
print(f"Map: {t3:.4f}s")
Typical results:
| Loop | 1.2s |
| Comprehension | 0.8s ← ~30% faster |
| Map | 0.9s |
💡 Why is comprehension faster? Python internally optimizes comprehensions with a special LIST_APPEND bytecode instruction that avoids method lookup overhead of .append().
9. Common Patterns
Pattern 1: Flatten Nested List
nested = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flat = [x for sublist in nested for x in sublist]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Pattern 2: Remove Duplicates (Order Preserved)
nums = [1, 3, 2, 1, 4, 3, 5]
seen = set()
unique = [x for x in nums if not (x in seen or seen.add(x))]
print(unique) # [1, 3, 2, 4, 5]
Pattern 3: Transpose Matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
# or using zip:
transposed2 = [list(row) for row in zip(*matrix)]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Pattern 4: Generate All Substrings
s = "abc"
substrings = [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]
print(substrings) # ['a', 'ab', 'abc', 'b', 'bc', 'c']
Pattern 5: Parse CSV-like data
csv_data = ["Alice,25,Delhi", "Bob,30,Mumbai", "Charlie,22,Bangalore"]
parsed = [
{"name": parts[0], "age": int(parts[1]), "city": parts[2]}
for line in csv_data
for parts in [line.split(",")] # trick: alias with single-element loop
]
print(parsed)
# [{'name': 'Alice', 'age': 25, 'city': 'Delhi'}, ...]
Pattern 6: Dictionary Filtering
config = {"debug": True, "log_level": "INFO", "max_retries": 3, "timeout": None}
# Remove None values
clean = {k: v for k, v in config.items() if v is not None}
print(clean) # {'debug': True, 'log_level': 'INFO', 'max_retries': 3}
10. Comprehension vs map/filter
nums = range(1, 11)
# map() – apply function to each element
# filter() – keep elements matching condition
# map + filter (old style)
result = list(map(lambda x: x**2, filter(lambda x: x%2==0, nums)))
print(result) # [4, 16, 36, 64, 100]
# Comprehension (Pythonic, readable)
result2 = [x**2 for x in nums if x % 2 == 0]
print(result2) # [4, 16, 36, 64, 100]
# Which is better?
# Comprehension: more readable, more Pythonic, slightly faster
# map/filter: better for complex functions already defined
def double(x): return x * 2
result3 = list(map(double, nums)) # Clean when function exists
11. Comprehension Gotchas
# ❌ Gotcha 1: Variable leakage (Python 2 issue, fixed in Python 3)
x = "outer"
result = [x for x in range(5)] # x in comprehension is local in Python 3
print(x) # "outer" ← Python 3 keeps outer x intact ✅
# ❌ Gotcha 2: Overly complex comprehensions
# Hard to read:
result = [x**2 for x in range(100) if x % 2 == 0 if x % 3 == 0 if x > 10]
# Better: use a function
def should_include(x):
return x % 2 == 0 and x % 3 == 0 and x > 10
result = [x**2 for x in range(100) if should_include(x)]
# ❌ Gotcha 3: Using comprehension for side effects
# Bad practice – comprehension for printing:
[print(x) for x in range(5)] # ❌ creates [None, None, ...] wastefully
# ✅ Use regular loop for side effects
for x in range(5):
print(x)
# ❌ Gotcha 4: Generator exhaustion
gen = (x**2 for x in range(5))
print(list(gen)) # [0, 1, 4, 9, 16]
print(list(gen)) # [] ← exhausted! Can only iterate once!
# ✅ Fix: Use list comprehension if multiple iterations needed
lst = [x**2 for x in range(5)]
print(list(lst)) # [0, 1, 4, 9, 16]
print(list(lst)) # [0, 1, 4, 9, 16] ← can reuse!
12. Interview Questions
Q1: List comprehension और for loop में क्या difference है?
List comprehension एक expression है जो new list return करता है। For loop statements हैं side effects के लिए। Comprehension typically faster (~30%) और more readable है। Use for loop when logic is complex or side effects needed।
Q2: Generator expression और list comprehension में क्या difference है?
List comprehension सारी values memory में store करता है ([]). Generator expression lazy है, values on-demand produce करता है (()). Large data के लिए generator, random access के लिए list।
Q3: Nested comprehension में for loops किस order में होते हैं?
Same order as nested for loops:
# [expr for outer in outer_it for inner in inner_it]
# is equivalent to:
# for outer in outer_it:
# for inner in inner_it:
# result.append(expr)
Q4: Dict comprehension से dictionary invert कैसे करें?
d = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in d.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
Q5: Comprehension में multiple conditions?
# AND conditions (multiple if)
result = [x for x in range(100) if x % 2 == 0 if x % 3 == 0]
# Same as: if x % 2 == 0 and x % 3 == 0
# OR conditions
result = [x for x in range(20) if x % 2 == 0 or x % 3 == 0]
Summary Cheatsheet
# ─── List Comprehension ───────────────────────────────
[expr for x in iterable]
[expr for x in iterable if condition]
[expr_if_true if cond else expr_if_false for x in iterable]
[expr for x in it1 for y in it2] # nested
# ─── Dict Comprehension ───────────────────────────────
{key: val for x in iterable}
{key: val for x in iterable if condition}
{v: k for k, v in d.items()} # invert dict
# ─── Set Comprehension ────────────────────────────────
{expr for x in iterable}
{expr for x in iterable if condition}
# ─── Generator Expression ─────────────────────────────
(expr for x in iterable)
(expr for x in iterable if condition)
sum(x**2 for x in range(10)) # no extra parens in function call
any(x < 0 for x in nums)
all(x > 0 for x in nums)
# ─── Comprehension vs Loop ────────────────────────────
# Comprehension → transforming/filtering data → new collection
# Loop → side effects, complex logic, multiple statements
🎯 Golden Rule: Comprehension use करें जब आप data को transform या filter करना चाहते हों और result एक collection हो। Complex side effects या multi-step logic के लिए regular loops prefer करें।
📤 Output Blocks (Missing Examples)
Conditional Comprehension Outputs
# Even numbers
nums = list(range(1, 21))
evens = [x for x in nums if x % 2 == 0]
print(evens)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# if-else labels
nums = list(range(1, 11))
labels = ["even" if x % 2 == 0 else "odd" for x in nums]
print(labels)
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
# FizzBuzz comprehension
fb = ["FizzBuzz" if x%15==0 else "Fizz" if x%3==0 else "Buzz" if x%5==0 else str(x)
for x in range(1, 16)]
print(fb)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
Nested Comprehension Outputs
# Matrix creation
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# Flatten 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [val for row in matrix for val in row]
print(flat)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# Cartesian product
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
products = [(c, s) for c in colors for s in sizes]
print(products)
[('red', 'S'), ('red', 'M'), ('red', 'L'), ('blue', 'S'), ('blue', 'M'), ('blue', 'L')]Dict & Set Comprehension Outputs
# Dict comprehension - word index
words = ["apple", "banana", "cherry"]
word_idx = {word: i for i, word in enumerate(words)}
print(word_idx)
{'apple': 0, 'banana': 1, 'cherry': 2}# Set comprehension - unique first letters
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
first_letters = {w[0] for w in words}
print(sorted(first_letters))
Generator Expression Outputs
import sys
list_c = [x**2 for x in range(1000)]
gen_e = (x**2 for x in range(1000))
print(f"List: {sys.getsizeof(list_c):,} bytes")
print(f"Gen: {sys.getsizeof(gen_e):,} bytes")
List: 8,856 bytes
Gen: 104 bytes
Walrus Operator Outputs
import math
nums = [4, -1, 9, 0, 16, -5, 25]
filtered = [root for x in nums if x > 0 and (root := math.sqrt(x)) > 2]
print(filtered)
texts = [" hello ", "", " ", "world", " python "]
cleaned = [s for t in texts if (s := t.strip())]
print(cleaned)
['hello', 'world', 'python']
⚠️ Common Mistakes
❌ Mistake 1: if-else position गलत रखना
# ❌ Wrong: if-else AFTER for (SyntaxError!)
result = [x for x in range(10) if x > 5 else 0] # SyntaxError
# ✅ Right: if-else BEFORE for (transformation)
result = [x if x > 5 else 0 for x in range(10)]
❌ Mistake 2: Side effects के लिए comprehension use करना
# ❌ Bad: Memory waste + unclear intent
[print(x) for x in range(10)] # Creates list of None values!
# ✅ Good: Use regular for loop for side effects
for x in range(10):
print(x)
❌ Mistake 3: Overly complex comprehension लिखना
# ❌ Unreadable one-liner
result = [x**2 + y for x in range(10) if x % 2 == 0 for y in range(x) if y % 3 == 0 and y > 1]
# ✅ Better: Break into a function or use regular loop
def process(x, y):
return x**2 + y
result = [process(x, y) for x in range(10) if x % 2 == 0
for y in range(x) if y % 3 == 0 and y > 1]
❌ Mistake 4: Generator को multiple times iterate करना
# ❌ Generator exhaust हो जाता है!
gen = (x**2 for x in range(5))
print(sum(gen)) # 30
print(sum(gen)) # 0 ← Empty! Generator exhausted!
# ✅ List use करें अगर multiple iterations चाहिए
lst = [x**2 for x in range(5)]
print(sum(lst)) # 30
print(sum(lst)) # 30 ← Works every time!
❌ Mistake 5: Nested comprehension में loop order confuse करना
# ❌ Wrong order assumption
# "Inner loop first" is WRONG in comprehension!
matrix = [[1,2], [3,4], [5,6]]
# ✅ Correct: Outer loop → Inner loop (left to right)
flat = [val for row in matrix for val in row]
# Same as: for row in matrix: for val in row: ...
❌ Mistake 6: Dict comprehension में duplicate keys ignore होना
# ❌ Last value wins! Duplicate keys silently overwrite
words = ["hello", "hi", "hey"]
result = {w[0]: w for w in words}
print(result) # {'h': 'hey'} ← Only last 'h' key survives!
# ✅ If you need all values, use list as value
from collections import defaultdict
d = defaultdict(list)
for w in words:
d[w[0]].append(w)
print(dict(d)) # {'h': ['hello', 'hi', 'hey']}
❌ Mistake 7: Large list comprehension में memory blow-up
# ❌ 10 million items in memory at once!
huge_list = [x**2 for x in range(10_000_000)]
# ✅ Generator use करें for large data
huge_gen = (x**2 for x in range(10_000_000))
total = sum(huge_gen) # Memory efficient!
✅ Key Takeaways
- 🎯 Comprehension = Concise + Fast — Traditional loop से ~30% faster होते हैं Python optimized bytecode की वजह से।
- 📋 List
[], Dict {}:, Set {}, Generator () — Syntax same, बस brackets अलग। Generator lazy है, बाकी eager। - 🔀 if-else BEFORE for = Transform —
[x if cond else y for ...], जबकि if AFTER for = Filter — [x for ... if cond]। - 🧠 Generator = Memory Efficient — Millions of items? Generator use करो, constant memory (~104 bytes) consume करता है।
- 🔄 Nested loops = Left to Right —
[expr for outer for inner] = outer loop first, inner loop second। Same order as nested for loops। - ⚡ Walrus
:= operator — Python 3.8+ में compute once, use twice pattern के लिए। Expensive functions को double-call से बचाता है। - 🚫 Side effects के लिए comprehension मत use करो —
[print(x) for ...] bad practice है। Regular loop use करो। - 📖 Readability > Cleverness — अगर comprehension 80+ characters या 2+ conditions हो, तो regular loop/function prefer करो।
- 🔁 Generator single-use है — Exhaust हो जाता है after one iteration। Multiple iterations चाहिए? List use करो।
- 🏆 Pythonic code = Comprehensions — Python interviews और production code में comprehensions preferred हैं over
map()/filter()।
❓ FAQ
Q1: Comprehension कब use करना चाहिए और कब नहीं?
Use करें जब data को transform या filter करना हो और result एक new collection हो। Use न करें जब logic complex हो (3+ conditions), side effects हों (print, file write), या readability suffer हो। Rule of thumb: अगर one line में 80 characters से ज़्यादा हो, तो loop prefer करें।
Q2: List comprehension और map() में कौन faster है?
List comprehension typically faster है simple operations के लिए because Python internally uses optimized bytecode (LIST_APPEND). But map() can be faster जब existing function apply कर रहे हो without lambda (e.g., map(str, nums))। Complex lambda के साथ comprehension always wins।
Q3: Generator expression कब use करें?
जब data बहुत large हो (millions of items), only one iteration needed हो, या early termination possible हो (any(), all())। Generator constant memory use करता है regardless of data size। But random access (gen[5]) या len() support नहीं करता।
Q4: {x for x in list} और set(list) में difference?
Functionally same — दोनों unique values देते हैं। But set comprehension allows filtering: {x for x in list if x > 0} — यह set(list) directly नहीं कर सकता। Performance almost identical है simple cases में।
Q5: Nested comprehension में loops कैसे read करें?
Left to right = Outer to Inner। [x for row in matrix for x in row] means: first loop over matrix (outer), then loop over each row (inner)। Exactly same order as writing nested for loops normally।
Q6: Walrus operator := comprehension में क्या advantage देता है?
Expensive computation को एक बार perform करके result store करता है। Without walrus, आपको same function दो बार call करना पड़ता — once for filtering, once for the value। := से performance improve होती है और code DRY रहता है।
Q7: Tuple comprehension क्यों नहीं होता Python में?
(expr for x in iterable) generator expression बनाता है, tuple नहीं! Tuple बनाने के लिए explicitly tuple(expr for x in iterable) लिखना पड़ता है। Python designers ने () syntax generators को दिया because generators ज़्यादा common use-case हैं।
Q8: Comprehension में break या continue use कर सकते हैं?
नहीं! ❌ Comprehensions expressions हैं, statements नहीं। break/continue statements हैं जो only loops में काम करते हैं। Alternative: filter condition use करें (if clause) या itertools.takewhile() / itertools.dropwhile() use करें।
🎯 Interview Questions
Q1: List comprehension internally कैसे काम करता है? Bytecode level पर क्या होता है?
Python list comprehension को internally एक separate code object में compile करता है। LIST_APPEND bytecode instruction directly list में item add करता है without .append() method lookup। यही reason है कि comprehension ~30% faster होता है regular loop से। Python 3 में comprehension का अपना scope होता है (variable leakage नहीं होती)।
Q2: Generator expression और generator function में क्या difference है?
Generator expression: (x2 for x in range(10)) — one-liner, simple transformations के लिए। Generator function**: yield keyword use करता है, complex stateful logic support करता है (multiple yields, try/except, send/throw)। दोनों lazy evaluation करते हैं, but function ज़्यादा powerful और reusable है।
Q3: Comprehension में variable scope कैसे काम करता है?
Python 3 में comprehension variables local होते हैं — outer scope affect नहीं होता: ``python x = "outer" result = [x for x in range(5)] print(x) # "outer" — unchanged! `` Python 2 में यह behavior different था (variable leak करता था)। यह Python 3 का major improvement है।
Q4: any() और all() के साथ generator use करने का क्या advantage है?
Short-circuit evaluation! any(x < 0 for x in million_items) — first True मिलते ही stop हो जाता है, सारे items check नहीं करता। Similarly all() first False पर stop करता है। List comprehension के साथ पहले सारे items evaluate होते, फिर check होता — wasteful!
Q5: Dictionary comprehension में collision (duplicate keys) handle कैसे करें?
Last value wins by default: ``python data = [("a", 1), ("b", 2), ("a", 3)] d = {k: v for k, v in data} # {'a': 3, 'b': 2} ` All values preserve करने के लिए collections.defaultdict(list) या setdefault()` use करें। Comprehension alone duplicate handling नहीं करता — यह interview में important point है।
Q6: Nested comprehension [[...] for ...] और flat comprehension [... for ... for ...] में difference explain करें।
Nested: [[j for j in range(3)] for i in range(3)] → list of lists बनाता है (2D structure)। Flat: [j for i in range(3) for j in range(3)] → single flat list बनाता है। Outer loop comes first in both cases, but result structure different है।
- Very large comprehensions (millions of items): Memory blow-up → Generator use करें - Complex expressions inside comprehension: Function call overhead - Multiple chained conditions: Readability और slight performance hit - Nested 3+ levels: Exponential time complexity possible Best practice: 2 levels तक nest करें, उससे ज़्यादा हो तो regular loops prefer करें।
Comprehension: Simple filter/transform, small-medium data, readable one-liners। itertools: Combinatorial operations (product, permutations), infinite iterators (count, cycle), chaining multiple iterables (chain), grouping (groupby)। itertools always lazy है और C-level optimized है।
Q9: Walrus operator := comprehension में use करते समय क्या pitfalls हैं?
- Readability suffer हो सकती है — team members को confuse कर सकता है - Python 3.8+ required — backward compatibility issue - Complex walrus expressions debugging difficult हैं - Order of evaluation matter करता है: if (y := f(x)) > 0 में y assign पहले होता है, compare बाद में Interview tip: Walrus use करें only जब performance gain measurable हो।
Q10: Real-world production code में comprehensions कैसे use होते हैं?
- Data cleaning: [row for row in csv_data if row['status'] == 'active'] - API response filtering: {item['id']: item for item in response['results']} - Config processing: {k: v for k, v in config.items() if v is not None} - Batch transformations: [transform(item) for item in batch] - Validation: all(validate(item) for item in data) Production rule: Keep comprehensions simple, add comments if logic isn't obvious, prefer named functions for complex transformations।