Part 04 / Topic 7 of 11
Basic comprehensions
A comprehension builds a list, dict or set in one line:
[expression for item in items if condition]. Read it as "make expression for each item in items, but only if condition". Use it for simple cases. If it gets long, use a normal loop.
Real-world example: prices with GST, and filtering marks.
prices = [100, 250, 400]
with_gst = [round(p * 1.18) for p in prices]
print(with_gst) # [118, 295, 472]
marks = {"Asha": 92, "Ravi": 38, "Meena": 75}
passed = [name for name, m in marks.items() if m >= 40]
print(passed) # ['Asha', 'Meena']
squares = {n: n * n for n in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}
emails = ["[email protected]", "[email protected]", "[email protected]"]
domains = {e.split("@")[1] for e in emails}
print(sorted(domains)) # ['gmail.com', 'yahoo.com']
| Kind | Syntax | Result |
|---|---|---|
| List | [x for x in items] |
list |
| Dict | {k: v for k, v in pairs} |
dict |
| Set | {x for x in items} |
set |
Generator expression: inside a call like sum(...), min(...) or max(...) you can drop the square brackets: sum(p * 2 for p in prices). This is a generator expression. It hands out one value at a time instead of building a full list first.
prices = [100, 250, 400]
print(sum(p * 2 for p in prices)) # 1500
๐ Going deeper: a generator expression saves memory on big data, because the full list is never built. The loop variable of a comprehension does not leak outside it: after
[n * 2 for n in range(3)], the namendoes not exist.
Done here? The practice set for Part 4 โ 8 exercises with solutions โ is on the part page.