A list comprehension builds a list from a loop in a single expression. You will see them everywhere in Python code, so being able to read and write them is essential.
From loop to comprehension
prices = [120, 450, 90, 300]
with_gst = []
for p in prices:
with_gst.append(p * 1.18)
with_gst = [p * 1.18 for p in prices] # same resultRead it as: "p times 1.18, for each p in prices".
Filtering with if
big = [p for p in prices if p >= 200]The if at the end keeps only matching items.
Choosing a value with if-else
labels = ["High" if p >= 200 else "Low" for p in prices]Note the position: an if-else that picks a value goes before for; a filtering if goes after it. Mixing these up is the most common comprehension error.
Working with strings
raw = [" pune", "INDORE ", "Surat"]
clean = [c.strip().title() for c in raw]Dictionary comprehensions
stock = {"pen": 120, "notebook": 0, "stapler": 15}
in_stock = {item: qty for item, qty in stock.items() if qty > 0}
price_after_discount = {k: round(v * 0.9) for k, v in prices_by_item.items()}Set comprehensions
domains = {email.split("@")[1] for email in emails}Unique email domains in one line.
Nested loops
pairs = [(size, colour) for size in ["S", "M", "L"] for colour in ["Red", "Blue"]]The loops run in the same order as if written as nested for statements. Flattening a list of lists works the same way:
flat = [x for row in matrix for x in row]When not to use a comprehension
- When the logic needs several steps or comments. A normal loop is clearer.
- When you only want the side effect (printing, writing to a file). Comprehensions are for building collections.
- In pandas, for column operations. Use vectorised methods like
df["price"] * 1.18instead of looping.
Generator expressions
Use round brackets to compute values lazily without building a full list:
total = sum(p * 1.18 for p in prices)Useful with sum, max, any and all on large data.
Practise
Our comprehensions set covers list, dictionary and set comprehensions, from simple transforms to filtering and nesting.
Practise what you just read
Reading helps; writing the code yourself is what sticks. Start here: