Part 10 / Topic 2 of 11
Comprehensions, advanced
A comprehension builds a list, dict or set in one expression: [expression for item in items if condition]. You met list comprehensions in Part 4. Here are the bigger forms.
Think of a cookie cutter on a conveyor belt: every item that passes the check is shaped the same way.
Dict and set comprehensions
orders = [("Asha", 1760), ("Ravi", 540), ("Meera", 2999)]
totals = {name: amount for name, amount in orders} # dict: {key: value ...}
print(totals) # {'Asha': 1760, 'Ravi': 540, 'Meera': 2999}
cities = {city for city in ["Pune", "Delhi", "Pune"]} # set: no duplicates
print(sorted(cities)) # ['Delhi', 'Pune']
if/else expression inside a comprehension
A conditional expression is a if condition else b. It goes at the front (it decides the value). A plain if at the end decides whether to keep the item.
amounts = [1760, 540, 2999, 820]
labels = ["big" if a >= 1000 else "small" for a in amounts] # transform every item
print(labels) # ['big', 'small', 'big', 'small']
big_only = [a for a in amounts if a >= 1000] # keep some items
print(big_only) # [1760, 2999]
Nested comprehensions
Write the for parts in the same order as normal nested loops.
grid = [[1, 2, 3], [4, 5, 6]]
flat = [cell for row in grid for cell in row]
print(flat) # [1, 2, 3, 4, 5, 6]
sizes = ["S", "M"]
colours = ["Red", "Blue"]
combos = [f"{c}-{s}" for c in colours for s in sizes]
print(combos) # ['Red-S', 'Red-M', 'Blue-S', 'Blue-M']
table = [[r * c for c in range(1, 4)] for r in range(1, 3)] # a list of lists
print(table) # [[1, 2, 3], [2, 4, 6]]
When NOT to use a comprehension
- More than two
fors, or anif/elseplus anif→ use a normal loop. - You only want a side effect (like
print) → use a normal loop, not[print(x) for x in items]. - The line needs a comment to explain it → it is too clever.
🔍 Going deeper: a comprehension has its own scope, so the loop variable does not leak out after the line (unlike a
forloop).
Done here? The practice set for Part 10 — 8 exercises with solutions — is on the part page.