Python List Comprehensions Cheat Sheet
Quick-reference for every comprehension pattern you actually use. Each section includes copy-ready snippets with inline output comments.
Basic List Comprehension
The simplest form: transform every item in an iterable into a new list.
squares = [x**2 for x in range(6)]
squares # => [0, 1, 4, 9, 16, 25]words = ['hello', 'world']
[w.upper() for w in words] # => ['HELLO', 'WORLD']raw = ['1', '2', '3']
nums = [int(x) for x in raw]
nums # => [1, 2, 3]lengths = [len(w) for w in ['hi', 'hello', 'hey']]
lengths # => [2, 5, 3]Filtering with if
Add an if clause after the iterable to include only matching items. Items that fail the condition are excluded entirely.
evens = [x for x in range(10) if x % 2 == 0]
evens # => [0, 2, 4, 6, 8]names = ['Alice', '', 'Bob', '', 'Carol']
[n for n in names if n] # => ['Alice', 'Bob', 'Carol'][x for x in range(20) if x % 2 == 0 if x % 3 == 0]
# => [0, 6, 12, 18]words = ['hello', 'WORLD', '123', 'foo']
[w for w in words if w.isalpha() and w.islower()]
# => ['hello', 'foo']If-Else (Ternary) in Comprehensions
Ternary if-else goes BEFORE the for clause and transforms every item (no exclusion). Filter if goes AFTER the iterable.
labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
labels # => ['even', 'odd', 'even', 'odd', 'even']nums = [3, -1, 4, -2, 0]
[x if x > 0 else 0 for x in nums] # => [3, 0, 4, 0, 0]data = ['a', None, 'b', None]
[x if x is not None else '?' for x in data]
# => ['a', '?', 'b', '?']Nested For Clauses
Multiple for clauses read left-to-right, matching the order of nested loops. The leftmost for is the outer loop.
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in matrix for n in row]
flat # => [1, 2, 3, 4, 5, 6]colors = ['red', 'blue']
sizes = ['S', 'M']
[(c, s) for c in colors for s in sizes]
# => [('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[n for row in matrix for n in row if n % 2 == 0]
# => [2, 4, 6, 8]# [expr for x in xs for y in ys] is equivalent to:
# result = []
# for x in xs:
# for y in ys:
# result.append(expr)Read for-clauses left-to-right: first for is outer, next for is inner.
Dict Comprehensions
Build a dictionary in one expression with {key: value for ...}.
words = ['hi', 'hello', 'hey']
{w: len(w) for w in words}
# => {'hi': 2, 'hello': 5, 'hey': 3}original = {'a': 1, 'b': 2, 'c': 3}
{v: k for k, v in original.items()}
# => {1: 'a', 2: 'b', 3: 'c'}prices = {'apple': 1.20, 'avocado': 3.50, 'banana': 0.80}
{k: v for k, v in prices.items() if v > 1.00}
# => {'apple': 1.20, 'avocado': 3.50}keys = ['name', 'age', 'city']
vals = ['Alice', 30, 'NYC']
dict(zip(keys, vals)) # => {'name': 'Alice', 'age': 30, 'city': 'NYC'}Set Comprehensions
Build a set with {expr for ...} (no colon). Duplicates are removed automatically.
names = ['Alice', 'BOB', 'alice', 'Bob']
{n.lower() for n in names}
# => {'alice', 'bob'}words = ['apple', 'avocado', 'banana', 'blueberry']
{w[0] for w in words} # => {'a', 'b'}nums = [1, 2, 2, 3, 3, 3, 4]
{x for x in nums if x > 1} # => {2, 3, 4}Generator Expressions
Use parentheses instead of brackets for lazy evaluation. Values are produced one at a time without building the full list in memory.
total = sum(x**2 for x in range(1000))
total # => 332833500nums = [2, 4, 6, 8]
all(x % 2 == 0 for x in nums) # => True
any(x > 10 for x in nums) # => False', '.join(str(x) for x in range(5))
# => '0, 1, 2, 3, 4'import sys
list_comp = [x for x in range(10_000)]
gen_expr = (x for x in range(10_000))
sys.getsizeof(list_comp) # => ~85176
sys.getsizeof(gen_expr) # => 200Generators are ideal when you iterate once. For reuse or random access, use a list.
Walrus Operator (:=) in Comprehensions
Python 3.8+ assignment expressions let you compute a value once, test it, and use the result — avoiding duplicate function calls.
# Without walrus: process() called twice
# [process(x) for x in data if process(x) > 0]
# With walrus: process() called once
results = [y for x in data if (y := process(x)) > 0]import re
texts = ['abc123', 'hello', 'x5y']
[m.group() for t in texts if (m := re.search(r'\d+', t))]
# => ['123', '5']lines = [' hello ', ' ', ' world ', '']
[clean for line in lines if (clean := line.strip())]
# => ['hello', 'world']Nested Comprehensions (2D)
A comprehension inside a comprehension produces nested structures like matrices.
matrix = [[0 for _ in range(3)] for _ in range(3)]
# => [[0, 0, 0], [0, 0, 0], [0, 0, 0]]m = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in m] for i in range(3)]
# => [[1, 4], [2, 5], [3, 6]]n = 4
[[1 if i == j else 0 for j in range(n)] for i in range(n)]
# => [[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]]When NOT to Use Comprehensions
Comprehensions are for building containers. Use regular loops when the intent is side effects, complex logic, or early exit.
# Bad: comprehension for side effects
[print(x) for x in items] # returns [None, None, ...]
# Good: plain loop
for x in items:
print(x)# Hard to read
# [f(x, y) for x in xs if p(x) for y in ys if q(x, y)]
# Clearer as a loop
result = []
for x in xs:
if p(x):
for y in ys:
if q(x, y):
result.append(f(x, y))# Can't break from a comprehension
for item in items:
if is_match(item):
result = item
breakRule of thumb: if you need break, continue, or multiple statements per iteration, use a loop.
Can you write this from memory?
Create a dict mapping numbers 1-3 to their squares using a dict comprehension