Skip to content

Python list comprehension

A list comprehension is a for loop folded into one line. Step through one below and watch each item go through the loop, the filter, and into the result.

step through it

The comprehension

[n * n for n in nums]

…is the same as this loop

result = []
for n in nums:
    result.append(n * n)

nums

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

Press Next to take the first item.

result

[]
0 / 5

▶ Run this in Python

The syntax

[expression  for item in iterable  if condition]
 └ what to add  └ the loop           └ optional filter

Read it from the middle: for each item in the iterable, if the condition holds, add the expression to the list. The colours in the explainer match these three parts in both versions, which is the fastest way to translate between loops and comprehensions in your head.

List comprehension examples

Squares 0–9
squares = [n * n for n in range(10)]
print(squares)
▶ Run
Filter
nums = [3, -1, 8, 0, -5, 12]
positive = [n for n in nums if n > 0]
print(positive)
▶ Run
if/else (same length)
nums = [3, -1, 8, 0, -5]
clamped = [n if n > 0 else 0 for n in nums]
print(clamped)
▶ Run
Flatten a 2D list
grid = [[1, 2, 3], [4, 5], [6]]
flat = [cell for row in grid for cell in row]
print(flat)
▶ Run
Pairs (two loops)
pairs = [(x, y) for x in "ab" for y in range(2)]
print(pairs)
▶ Run
Dict comprehension
words = ["python", "sql", "rust"]
lengths = {w: len(w) for w in words}
print(lengths)
▶ Run
Set comprehension
emails = ["A@x.com", "b@y.com", "a@X.com"]
domains = {e.split("@")[1].lower() for e in emails}
print(domains)
▶ Run
Generator expression
total = sum(n * n for n in range(1_000_000))
print(total)
▶ Run
With a function
import re
lines = ["id: 42", "none here", "id: 7"]
ids = [int(m.group(1)) for line in lines if (m := re.search(r"id: (\d+)", line))]
print(ids)
▶ Run

Comprehension or loop?

Use a comprehension when you are building a new collection from an existing one with a single expression and at most a simple filter. Switch back to a regular loop when you need multiple statements, error handling or side effects. PEP 202 introduced list comprehensions in Python 2.0; PEP 274 added dict and set comprehensions.

More Python syntax on the Python cheat sheet, and string formatting in the f-string guide.

Frequently asked questions

What is a list comprehension in Python?

A compact expression that builds a list from an iterable: [expression for item in iterable if condition]. It does the same job as a for loop that appends to a list, in one readable line.

Are list comprehensions faster than for loops?

Usually a little, because the append happens in optimised bytecode instead of a method call per item. The bigger win is readability; don’t contort logic into a comprehension for speed.

Where does if go: before or after for?

A filter goes at the end: [x for x in xs if x > 0]. A choice between two values goes in the expression at the front: [x if x > 0 else 0 for x in xs]. The first drops items, the second keeps the same length.

How do nested list comprehensions work?

The for clauses read in the same order as nested loops: [cell for row in grid for cell in row] is for row in grid: for cell in row: append(cell). It flattens a 2D list.

When should I not use a list comprehension?

When the body needs several statements, try/except, or side effects like printing. When you only need to iterate once (for sum, any, max), use a generator expression without square brackets to avoid building a list.