Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. Python
  4. Python List Comprehensions Cheat Sheet
PythonCheat Sheet

Python List Comprehensions Cheat Sheet

Quick-reference for every comprehension pattern you actually use. Each section includes copy-ready snippets with inline output comments.

On this page
  1. 1Basic List Comprehension
  2. 2Filtering with if
  3. 3If-Else (Ternary) in Comprehensions
  4. 4Nested For Clauses
  5. 5Dict Comprehensions
  6. 6Set Comprehensions
  7. 7Generator Expressions
  8. 8Walrus Operator (:=) in Comprehensions
  9. 9Nested Comprehensions (2D)
  10. 10When NOT to Use Comprehensions
Basic List ComprehensionFiltering with ifIf-Else (Ternary) in ComprehensionsNested For ClausesDict ComprehensionsSet ComprehensionsGenerator ExpressionsWalrus Operator (:=) in ComprehensionsNested Comprehensions (2D)When NOT to Use Comprehensions

Basic List Comprehension

The simplest form: transform every item in an iterable into a new list.

Square each number
squares = [x**2 for x in range(6)]
squares   # => [0, 1, 4, 9, 16, 25]
Uppercase each string
words = ['hello', 'world']
[w.upper() for w in words]   # => ['HELLO', 'WORLD']
Convert types
raw = ['1', '2', '3']
nums = [int(x) for x in raw]
nums   # => [1, 2, 3]
Call a function on each item
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.

Keep even numbers
evens = [x for x in range(10) if x % 2 == 0]
evens   # => [0, 2, 4, 6, 8]
Filter non-empty strings
names = ['Alice', '', 'Bob', '', 'Carol']
[n for n in names if n]   # => ['Alice', 'Bob', 'Carol']
Multiple if conditions (same as and)
[x for x in range(20) if x % 2 == 0 if x % 3 == 0]
# => [0, 6, 12, 18]
Filter with method call
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.

Classify even/odd
labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
labels   # => ['even', 'odd', 'even', 'odd', 'even']
Clamp negatives to zero
nums = [3, -1, 4, -2, 0]
[x if x > 0 else 0 for x in nums]   # => [3, 0, 4, 0, 0]
Default on None
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.

Flatten a 2D list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in matrix for n in row]
flat   # => [1, 2, 3, 4, 5, 6]
All pairs (Cartesian product)
colors = ['red', 'blue']
sizes = ['S', 'M']
[(c, s) for c in colors for s in sizes]
# => [('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
Nested with filter
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]
Equivalent nested loop
# [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 ...}.

Word-to-length mapping
words = ['hi', 'hello', 'hey']
{w: len(w) for w in words}
# => {'hi': 2, 'hello': 5, 'hey': 3}
Invert a dict (swap keys and values)
original = {'a': 1, 'b': 2, 'c': 3}
{v: k for k, v in original.items()}
# => {1: 'a', 2: 'b', 3: 'c'}
Filter a dict by value
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}
From two lists with zip
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.

Unique lowercase names
names = ['Alice', 'BOB', 'alice', 'Bob']
{n.lower() for n in names}
# => {'alice', 'bob'}
Unique first characters
words = ['apple', 'avocado', 'banana', 'blueberry']
{w[0] for w in words}   # => {'a', 'b'}
Set from filtered data
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.

Sum without allocating a list
total = sum(x**2 for x in range(1000))
total   # => 332833500
any() and all() with generators
nums = [2, 4, 6, 8]
all(x % 2 == 0 for x in nums)   # => True
any(x > 10 for x in nums)       # => False
Pass to join()
', '.join(str(x) for x in range(5))
# => '0, 1, 2, 3, 4'
Generator vs list memory
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)    # => 200

Generators 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.

Filter and use an expensive result
# 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]
Assign and filter in one step
import re
texts = ['abc123', 'hello', 'x5y']
[m.group() for t in texts if (m := re.search(r'\d+', t))]
# => ['123', '5']
Strip and check non-empty
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.

Create a matrix
matrix = [[0 for _ in range(3)] for _ in range(3)]
# => [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Transpose a matrix
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]]
Identity matrix
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.

Side effects: use a loop
# Bad: comprehension for side effects
[print(x) for x in items]   # returns [None, None, ...]

# Good: plain loop
for x in items:
    print(x)
Too complex: use a loop or helper
# 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))
Need early exit: use a loop
# Can't break from a comprehension
for item in items:
    if is_match(item):
        result = item
        break

Rule of thumb: if you need break, continue, or multiple statements per iteration, use a loop.

Learn Python in Depth
Python Collections Practice →Python Loops Practice →Python Strings Practice →
Warm-up1 / 2

Can you write this from memory?

Create a dict mapping numbers 1-3 to their squares using a dict comprehension

See Also
Loops →Dictionary Methods →String Methods →

Start Practicing Python

Free daily exercises with spaced repetition. No credit card required.

← Back to Python Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.