Comprehensions

Topic 5 of 5 in Collections6 min readBeginnerFree course

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

Python
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”.

Anatomy of a list comprehension: [ p * 1.2 for p in prices if p > 10 ]. p * 1.2 is what to keep; for p in prices loops over the items; and if p > 10 is an optional filter. It does the same thing as the loop: result = [], then for p in prices: if p > 10: result.append(p * 1.2).

The parts:

  1. the expression — what each new item should be (p * 1.2);
  2. the loop — where the items come from (for p in prices);
  3. an optional filter — which items to keep (if p > 10).
Python
expensive_with_tax = [p * 1.2 for p in prices if p > 10]
# [15.0, 24.0]

That’s exactly equivalent to:

Python
expensive_with_tax = []
for p in prices:
    if p > 10:
        expensive_with_tax.append(p * 1.2)

More examples

Python
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 strings

Comprehensions can unpack, just like for loops:

Python
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:

Python
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:

Python
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 values

Generator 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:

Python
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

Python
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 of Nones. Just write a for loop.

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 …).

Exercise

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.

Python
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 food

Summary

  • [expression for item in items] builds a new list from every item.
  • Add if condition at the end to keep only some items.
  • a if condition else b in 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 inside sum, max, any, all.
  • Use comprehensions for simple transform-and-filter steps; switch to a normal loop when the logic needs several lines.