Comprehension
Comprehensions are a concise, readable way to build collections in one expression.
List Comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# equivalent for loop
result = []
for x in range(10):
result.append(x**2)
Dict Comprehension
word_len = {word: len(word) for word in ["hello", "world", "python"]}
# {'hello': 5, 'world': 5, 'python': 6}
inverted = {v: k for k, v in {"a": 1, "b": 2}.items()}
# {1: 'a', 2: 'b'}
Set Comprehension
unique_lens = {len(word) for word in ["hi", "hello", "hey"]}
# {2, 5, 3}
Generator Expression
Like a list comprehension but lazy — evaluates one item at a time, no memory overhead.
gen = (x**2 for x in range(1_000_000)) # no list created
total = sum(x**2 for x in range(1_000_000)) # efficient
Nested Comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
grid = [(x, y) for x in range(3) for y in range(3)]
Conditional Expression (ternary)
result = [x if x > 0 else -x for x in [-1, 2, -3, 4]]
# [1, 2, 3, 4] — absolute values
Key Interview Points
- List comprehension is O(n) memory; generator expression is O(1) memory.
- Prefer a plain
forloop when the logic is complex — readability matters. - Generator expressions work inside function calls without extra parentheses:
sum(x**2 for x in data). - Nested comprehensions read left to right, same order as nested
forloops. {k: v for ...}is a dict comprehension;{v for ...}is a set comprehension.