Comprehensions
A comprehension builds a new list, dict or set from another collection in one expression: [x * 2 for x in numbers if x > 0]. It reads as "give me this, for each item, if a condition holds". Use comprehensions for simple transforms and filters; switch to a normal loop when the logic needs more than one line.
From loop to comprehension
prices = [10, 25, 8, 40]
# the loop way
with_vat = []
for p in prices:
with_vat.append(round(p * 1.21, 2))
print(with_vat)
# the comprehension way
print([round(p * 1.21, 2) for p in prices])[12.1, 30.25, 9.68, 48.4] [12.1, 30.25, 9.68, 48.4]
The pattern is [expression for item in iterable]. The expression decides what goes into the new list.
Filtering with if
words = ["python", "AI", "data", "ML", "pandas"]
long_words = [w for w in words if len(w) > 2]
print(long_words)
labels = ["big" if len(w) > 4 else "small" for w in words]
print(labels)['python', 'data', 'pandas'] ['big', 'small', 'small', 'small', 'big']
Dict and set comprehensions
names = ["ana", "ben", "cara"]
lengths = {name: len(name) for name in names}
print(lengths)
prices = {"tea": 2.5, "cake": 4.0, "coffee": 3.2}
cheap = {k: v for k, v in prices.items() if v < 3.5}
print(cheap)
emails = ["a@x.com", "b@y.org", "c@x.com"]
print(sorted({e.split("@")[1] for e in emails})){'ana': 3, 'ben': 3, 'cara': 4}
{'tea': 2.5, 'coffee': 3.2}
['x.com', 'y.org']Nested loops
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [n for row in matrix for n in row]
print(flat)
pairs = [(x, y) for x in range(2) for y in range(3)]
print(pairs)[1, 2, 3, 4, 5, 6] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
Read nested for parts left to right, in the same order you'd write the loops. Two levels is the readable limit — beyond that, use normal loops.
Generator expressions
numbers = range(1, 1_000_001)
print(sum(n * n for n in numbers))
print(any(n > 999_999 for n in numbers))333333833333500000 True
Round brackets instead of square ones create a generator: it produces values one at a time instead of building a whole list in memory. Perfect inside sum(), any(), all(), max().
Practice
From temps = {"Mon": 12, "Tue": 19, "Wed": 23, "Thu": 17} print, with comprehensions: a list of the days warmer than 15 degrees, then a dict that maps each day to its temperature in Fahrenheit (c * 9 / 5 + 32).
['Tue', 'Wed', 'Thu']
{'Mon': 53.6, 'Tue': 66.2, 'Wed': 73.4, 'Thu': 62.6}