Intermediate Python · Lesson 4 of 14
Comprehensions: list, dict and set
Build lists, dictionaries and sets in one readable line, filter with if, choose values with if/else, and handle nested data with nested loops.
A comprehension builds a new collection from an existing one in a single expression. It replaces the common pattern of an empty list, a for loop and append. You met the list comprehension briefly in the beginners' course; here is the full picture.
prices = [4.0, 12.5, 8.0, 30.0]
with_vat = []
for p in prices:
with_vat.append(p * 1.2)
print(with_vat)
with_vat = [p * 1.2 for p in prices]
print(with_vat)[4.8, 15.0, 9.6, 36.0] [4.8, 15.0, 9.6, 36.0]
The loop and the comprehension give the same list.
Filtering and choosing
An if at the end filters: items that fail the test are skipped. An if ... else at the start keeps every item but picks one of two values for it. Mixing the two up is a common mistake.
scores = [45, 82, 67, 91, 38]
passed = [s for s in scores if s >= 50]
print(passed)
labels = ["pass" if s >= 50 else "fail" for s in scores]
print(labels)
words = [" Tea ", "coffee", " ", "Juice "]
clean = [w.strip().lower() for w in words if w.strip()]
print(clean)[82, 67, 91] ['fail', 'pass', 'pass', 'pass', 'fail'] ['tea', 'coffee', 'juice']
Dictionary and set comprehensions
Curly brackets with key: value make a dict comprehension. Curly brackets with a single value make a set comprehension, which drops duplicates. Sets have no fixed order, so sort them before printing.
prices = {"bread": 2.0, "cheese": 7.5, "olives": 4.0}
with_vat = {item: round(p * 1.1, 2) for item, p in prices.items()}
print(with_vat)
expensive = {item: p for item, p in prices.items() if p > 3}
print(expensive)
codes = {"GR": "Greece", "JP": "Japan", "BR": "Brazil"}
by_name = {name: code for code, name in codes.items()}
print(by_name)
cities = ["Paris", "Porto", "Lima", "London", "Lagos"]
initials = {c[0] for c in cities}
print(sorted(initials)){'bread': 2.2, 'cheese': 8.25, 'olives': 4.4}
{'cheese': 7.5, 'olives': 4.0}
{'Greece': 'GR', 'Japan': 'JP', 'Brazil': 'BR'}
['L', 'P']Nested comprehensions
A comprehension can have more than one for. Read them in the same order as nested loops: the first for is the outer loop.
weeks = [[3, 5, 2], [4, 0], [6, 1, 1]]
all_days = [n for week in weeks for n in week]
print(all_days)
sizes = ["S", "M"]
colours = ["red", "blue"]
variants = [f"{s}-{c}" for s in sizes for c in colours]
print(variants)
table = [[row * col for col in range(1, 4)] for row in range(1, 4)]
print(table)[3, 5, 2, 4, 0, 6, 1, 1] ['S-red', 'S-blue', 'M-red', 'M-blue'] [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
for parts or a long condition, write a normal loop instead. Readable code beats short code.✎ Exercise
From the list of words, build a dictionary that maps each word (in lower case) to its length, but only for words longer than 3 letters.
Hint: Use {key: value for w in words if condition} with w.lower() as the key and len(w) as the value.
words = ["Sun", "Mountain", "river", "Sea", "Forest", "Lake"]
# your code here
Expected output:
{'mountain': 8, 'river': 5, 'forest': 6, 'lake': 4}Show a solution
words = ["Sun", "Mountain", "river", "Sea", "Forest", "Lake"]
lengths = {w.lower(): len(w) for w in words if len(w) > 3}
print(lengths){'mountain': 8, 'river': 5, 'forest': 6, 'lake': 4}Check yourself
1. What does [x * 2 for x in range(4) if x % 2 == 1] give?
Only the odd numbers 1 and 3 pass the filter, and each is doubled.
2. Where does the if ... else go when you want to keep every item but change some?
[a if test else b for x in items] keeps every item. An if at the end only filters.
3. What kind of collection does {w[0] for w in words} create?
Curly brackets with a single expression (no colon) make a set.