TExcelTAD
Home › Python › Python Comprehensions

Python Comprehensions

A comprehension builds a new list, dict or set from an existing iterable in a single, readable expression. It replaces the common "create an empty list, loop, append" pattern.

List comprehensions

Compare the loop version with the comprehension:

python · try it yourself
numbers = [1, 2, 3, 4, 5]

squares = []
for n in numbers:
    squares.append(n * n)
print(squares)

squares = [n * n for n in numbers]
print(squares)
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

Read it as: "n * n for each n in numbers". The general shape is:

python
[expression for item in iterable]
[expression for item in iterable if condition]

Filtering with if

Add an if at the end to keep only some items:

python · try it yourself
words = ["sky", "Python", "is", "a", "joy", "Comprehension"]
long_words = [w for w in words if len(w) > 3]
print(long_words)

prices = [12.5, 0, 7.25, 0, 3]
print([p for p in prices if p])          # drop zeros
print([w.lower() for w in words if w[0].isupper()])
['Python', 'Comprehension']
[12.5, 7.25, 3]
['python', 'comprehension']

Choosing a value with if/else

To transform every item differently rather than filter, put a conditional expression at the front:

python · try it yourself
scores = [45, 82, 67, 91, 38]
results = ["pass" if s >= 50 else "fail" for s in scores]
print(results)

capped = [min(s, 80) for s in scores]
print(capped)
['fail', 'pass', 'pass', 'pass', 'fail']
[45, 80, 67, 80, 38]
Position Syntax Effect
End [x for x in xs if cond] filters — fewer items
Front [a if cond else b for x in xs] maps — same number of items

Nested loops

Several for clauses work like nested loops, in the same order you'd write them:

python · try it yourself
pairs = [(x, y) for x in [1, 2, 3] for y in "ab"]
print(pairs)

matrix = [[1, 2, 3], [4, 5, 6]]
flat = [n for row in matrix for n in row]
print(flat)

transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
[1, 2, 3, 4, 5, 6]
[[1, 4], [2, 5], [3, 6]]

Dictionary and set comprehensions

Curly braces give you dict and set comprehensions. A dict comprehension needs a key: value expression:

python · try it yourself
fruits = ["apple", "kiwi", "banana"]
lengths = {f: len(f) for f in fruits}
print(lengths)

prices = {"tea": 2.0, "cake": 4.5, "juice": 3.0}
discounted = {item: round(p * 0.9, 2) for item, p in prices.items() if p > 2.5}
print(discounted)

swapped = {v: k for k, v in {"a": 1, "b": 2}.items()}
print(swapped)

initials = {name[0] for name in ["Anh", "Bao", "An", "Binh"]}
print(sorted(initials))
{'apple': 5, 'kiwi': 4, 'banana': 6}
{'cake': 4.05, 'juice': 2.7}
{1: 'a', 2: 'b'}
['A', 'B']

Generator expressions

With parentheses you get a generator expression. It produces items lazily, one at a time, without building a list in memory — ideal when you only need to feed the values into a function like sum(), max() or any():

python · try it yourself
total = sum(n * n for n in range(1, 1001))
print(total)

words = ["alpha", "beta", "gamma"]
print(any(w.startswith("g") for w in words))
print(max(len(w) for w in words))

gen = (n * 2 for n in range(3))
print(gen.__class__.__name__, list(gen))
333833500
True
5
generator [0, 2, 4]

When a generator expression is the only argument, you can drop the extra parentheses: sum(x for x in data).

When not to use a comprehension

Comprehensions are for building collections. If you're only running code for its side effects (printing, writing to a file), use a plain loop. And if a comprehension needs three fors and two ifs, a regular loop is probably clearer.

Tip: Comprehensions have their own scope: the loop variable doesn't leak out. After [x for x in range(3)], the name x is not defined (unless it existed before).

Test yourself

What does [x * 2 for x in range(4) if x % 2 == 0] produce?

  1. [0, 2, 4, 6]
  2. [0, 4]
  3. [2, 6]
  4. [0, 2]

Which brackets create a dictionary comprehension?

  1. [k: v for ...]
  2. (k: v for ...)
  3. {k: v for ...}
  4. <k: v for ...>

What is the main advantage of a generator expression like sum(x*x for x in data)?

  1. It's always faster to write
  2. It doesn't build a full list in memory
  3. It sorts the data
  4. It can be reused many times