What is a comprehension?#
A comprehension is a short, readable way to create a new list, dict or set from an existing sequence - in one line.
Without a comprehension:
squares = []
for n in range(1, 6):
squares.append(n * n)
With a list comprehension:
squares = [n * n for n in range(1, 6)]
Both give [1, 4, 9, 16, 25].
Basic syntax#
[expression for item in iterable]
Read it as: "give me expression for each item in iterable".
List comprehension को एक वाक्य की तरह पढ़ें:
[n * n for n in range(1, 6)] → "1 से 5 तक हर n के लिए, n * n दो।"
इसमें तीन हिस्से हैं:
- क्या चाहिए -
n * n(हर item पर क्या करना है) - किस पर loop -
for n in range(1, 6) - (वैकल्पिक) शर्त -
if ...(कौन-से items रखने हैं)
यह 3-4 लाइन के for loop + append का छोटा और तेज़ रूप है।
Filtering with if#
Add if condition at the end to keep only some items:
[expression for item in iterable if condition]
Choosing values with if-else#
To transform every item into one of two values, put if-else before for:
[value_if_true if condition else value_if_false for item in iterable]
Position matters:
- Filter (drop items):
[x for x in data if x > 0]-ifat the end, noelse. - Choose (keep all items):
[x if x > 0 else 0 for x in data]-if-elsebeforefor.
[x for x in data if x > 0 else 0] is a SyntaxError.
Nested loops in a comprehension#
The for clauses are written in the same order as nested loops:
Dictionary comprehensions#
{key_expr: value_expr for item in iterable}
Set comprehensions#
Generator expressions#
Using round brackets creates a generator - it produces values one at a time instead of building a whole list in memory. Great with sum, max, any, all:
You'll learn more about generators in the next lesson.
When NOT to use comprehensions#
Comprehensions are great for simple transformations. If it needs several conditions, nested if-else, or side effects (printing, writing files), use a normal loop:
# Hard to read - avoid
result = [x * 2 if x > 0 else x * -1 if x < -10 else 0 for x in data if x != 5]
# Not for side effects - avoid
[print(x) for x in data] # use a for loop instead
Rule of thumb: if the comprehension doesn't fit comfortably on one line, or you have to read it twice, write a regular loop.
Summary#
[expr for x in items]- build a list in one line.[expr for x in items if cond]- filter items.[a if cond else b for x in items]- choose a value for every item.{k: v for ...}→ dict;{expr for ...}→ set;(expr for ...)→ generator.- Keep comprehensions short and simple; use loops for complex logic.