Comprehensions
Overview
In Loop patterns you built new lists with a loop: start with [], loop, append. That pattern is so common that Python has a dedicated syntax for it — the comprehension — which says the same thing in one readable line.
List comprehensions
prices = [4.0, 12.5, 8.0, 20.0]
with_tax = [p * 1.2 for p in prices]
# [4.8, 15.0, 9.6, 24.0]Read it as: “a list of p * 1.2, for each p in prices”.
The parts:
- the expression — what each new item should be (
p * 1.2); - the loop — where the items come from (
for p in prices); - an optional filter — which items to keep (
if p > 10).
expensive_with_tax = [p * 1.2 for p in prices if p > 10]
# [15.0, 24.0]That’s exactly equivalent to:
expensive_with_tax = []
for p in prices:
if p > 10:
expensive_with_tax.append(p * 1.2)More examples
squares = [n ** 2 for n in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [n for n in range(20) if n % 2 == 0] # filter only
words = [w.strip().lower() for w in raw_words] # clean up text
lengths = [len(name) for name in names]
first_letters = [name[0] for name in names if name] # skip empty stringsComprehensions can unpack, just like for loops:
pairs = [("Asha", 91), ("Ben", 78)]
names = [name for name, score in pairs]
passed = [name for name, score in pairs if score >= 80]Choosing values: if/else in the expression
A filter if at the end drops items. To transform each item one of two ways, put a conditional expression at the start:
labels = ["pass" if s >= 50 else "fail" for s in scores]The position tells you which is which:
[x for x in items if test]— keep only some items;[a if test else b for x in items]— keep every item, choose its value.
Dictionary and set comprehensions
Change the brackets and you get other collections:
names = ["Asha", "Ben", "Chen"]
{name: len(name) for name in names} # dict: {'Asha': 4, 'Ben': 3, 'Chen': 4}
{len(name) for name in names} # set: {3, 4}
prices = {"tea": 3.5, "cake": 5.25}
{item: p * 2 for item, p in prices.items()} # double every price
{p: item for item, p in prices.items()} # swap keys and valuesGenerator expressions
With round brackets, you get a generator expression. It doesn’t build a list at all; it produces items one at a time as they’re needed. That’s perfect when you only need to feed values into a function:
total = sum(p * 1.2 for p in prices) # no temporary list
longest = max(len(w) for w in words)
any_negative = any(n < 0 for n in numbers)
all_valid = all(email.count("@") == 1 for email in emails)When a generator expression is the only argument, you don’t need extra brackets. Generators save memory with big data and can stop early (any stops at the first True). Iterators and generators explains how they work.
Nested loops in a comprehension
pairs = [(x, y) for x in range(3) for y in range(2)]
# [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
grid = [[1, 2], [3, 4]]
flat = [n for row in grid for n in row] # [1, 2, 3, 4]The for clauses go in the same order as nested loops would. This is where comprehensions start to get hard to read — use them sparingly.
When not to use a comprehension
Comprehensions are for building a collection. Avoid them when:
- the logic needs several steps, nested conditions or error handling — a normal loop is clearer;
- you’re doing it for side effects:
[print(x) for x in items]builds a useless list ofNones. Just write aforloop.
A good test: if you can’t read the comprehension aloud as one sentence, write a loop.
Remember:
[what for item in items if keep]— and swap the brackets for a dict{k: v …}, a set{x …}, or a generator(x …).
Clean up product data
Using comprehensions only (no append loops): (1) a list of all product names in upper case; (2) a list of names of products that cost more than 10; (3) a dictionary mapping each name to its price including 20% tax, rounded to 2 places; (4) a set of the categories; (5) a list of labels, "sale" if the price is under 5 otherwise "regular"; (6) the total price of all food items using sum() with a generator expression. Print each result.
products = [
("Notebook", 3.5, "stationery"),
("Coffee", 12.0, "food"),
("Pen", 1.25, "stationery"),
("Tea", 6.75, "food"),
("Backpack", 45.0, "bags"),
]
# 1. Names in upper case
# 2. Names of products over 10
# 3. Name → price with 20% tax
# 4. Set of categories
# 5. "sale" / "regular" labels
# 6. Total price of foodproducts = [
("Notebook", 3.5, "stationery"),
("Coffee", 12.0, "food"),
("Pen", 1.25, "stationery"),
("Tea", 6.75, "food"),
("Backpack", 45.0, "bags"),
]
# 1. Names in upper case
print([name.upper() for name, price, category in products])
# 2. Names of products over 10
print([name for name, price, category in products if price > 10])
# 3. Name → price with 20% tax
print({name: round(price * 1.2, 2) for name, price, category in products})
# 4. Set of categories
print(sorted({category for name, price, category in products}))
# 5. "sale" / "regular" labels
print(["sale" if price < 5 else "regular" for name, price, category in products])
# 6. Total price of food
print(sum(price for name, price, category in products if category == "food"))Summary
[expression for item in items]builds a new list from every item.- Add
if conditionat the end to keep only some items. a if condition else bin the expression part chooses between two values for each item.{k: v for …}builds a dict,{x for …}a set, and(x for …)a lazy generator — ideal insidesum,max,any,all.- Use comprehensions for simple transform-and-filter steps; switch to a normal loop when the logic needs several lines.