Python Comprehensions
A comprehension is a concise way to build a list or dictionary directly from an iterable, without writing an explicit accumulator for-loop.
List comprehension
>>> [k**2 for k in range(4)]
[0, 1, 4, 9]
Equivalent to:
>>> acc = []
>>> for k in range(4):
... acc.append(k**2)
sum(... for ...) (a generator expression, without the surrounding []) computes a running total directly, without building the intermediate list:
>>> sum(k**2 for k in range(4))
14
Dictionary comprehension
>>> {x: x**2 for x in range(4)}
{0: 0, 1: 1, 2: 4, 3: 9}
Useful for assigning default values across a set of keys:
>>> {x: 0 for x in "ABC"}
{'A': 0, 'B': 0, 'C': 0}
Nested comprehensions
Multiple for clauses can appear in one comprehension. The order of the for clauses matters — it matches the order they’d be nested as for-loops:
>>> [(a, x) for a in "AB" for x in range(2)]
[('A', 0), ('A', 1), ('B', 0), ('B', 1)]
>>> [(a, x) for x in range(2) for a in "AB"]
[('A', 0), ('B', 0), ('A', 1), ('B', 1)]
Filtering
A trailing if filters which elements are included:
>>> [x for x in range(101) if not (x % 3) and not (x % 7)]
[0, 21, 42, 63, 84]
The general pattern
[x for x in xs if P(x)]
[x for x in xs for y in ys if P(x, y)]
[x for x in xs for y in ys for z in zs if P(x, y, z)]
...
where P is some predicate.
True/False as 1/0
Python’s bool is a subtype of int, so True/False behave as 1/0 in arithmetic — a common idiom for counting how many elements of an iterable satisfy some condition:
>>> True + True + False
2
>>> sum(x > 0 for x in [-1, 2, 3, -4])
2
all and any
Python’s built-in all(xs)/any(xs) check whether every/some element of xs is truthy:
>>> all(['A' <= x <= 'Z' for x in "HELLO WORLD"])
False
>>> any(['A' <= x <= 'Z' for x in "HELLO WORLD"])
True
Careful: redefining a function named
alloranyin your own code shadows these built-ins for the rest of that scope — see 2025-08-25-comprehensions’s exercises, which do exactly this (as an exercise in reimplementing them) as a worked example.
See python-for-loops for the equivalent for-loop/accumulator forms these shortcut.