A Python list comprehension builds a new list from an iterable in one expression: [expression for item in iterable if condition]. For example, [n * n for n in nums if n % 2 == 0] gives the squares of the even numbers in nums, which would otherwise take a four-line for loop with append().
nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
print(squares) # [1, 4, 9, 16, 25, 36]
Every example below was run on Python 3.12.2, and the output shown is the real output.
List comprehension syntax
The Python tutorial defines it like this: "A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses." Read it left to right as "give me expression, for each item in iterable, if condition".
result = [expression for item in iterable if condition]
# is equivalent to
result = []
for item in iterable:
if condition:
result.append(expression)
Comprehensions arrived in Python 2.0 via PEP 202, which describes them as a more concise way to create lists where you would otherwise use map(), filter() or nested loops.
Filtering with if
An if at the end keeps only the items that pass the test:
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens) # [2, 4, 6]
Common real-world filters: [line for line in lines if line.strip()] drops blank lines, and [f for f in files if f.endswith(".csv")] keeps CSV file names.
if/else in a list comprehension
To transform every item one way or another, put a conditional expression at the front, before for:
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even']
The position is the source of the most common error. A filter if goes at the end and has no else. A value-choosing if ... else goes at the front and must have an else. Putting an if without else at the front fails:
>>> [n if n > 2 for n in [1, 2, 3]]
SyntaxError: expected 'else' after 'if' expression
You can use both in one comprehension: ["big" if n > 4 else "small" for n in nums if n % 2 == 0] filters to even numbers first, then labels each one.
Nested list comprehensions
Multiple for clauses run in the same order as nested loops written top to bottom. Flattening a list of lists:
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row]
print(flat) # [1, 2, 3, 4, 5, 6]
Read it as "for row in matrix, for x in row, give x". The order trips people up because the expression comes first but the loops read outer to inner. Every combination of two sequences works the same way:
pairs = [(a, b) for a in range(2) for b in "ab"]
print(pairs) # [(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]
A comprehension inside the expression builds a list of lists instead. This transposes rows and columns:
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # [[1, 4], [2, 5], [3, 6]]
The Python tutorial shows the same transpose and then recommends the built-in for real code: list(zip(*matrix)), which returns tuples instead of lists.
Dict and set comprehensions
The same syntax works with curly braces. A key: value pair makes a dict; a single expression makes a set:
words = ["apple", "Banana", "cherry"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'Banana': 6, 'cherry': 6}
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}
There is no "tuple comprehension". Parentheses create a generator expression, covered next.
Generator expressions: when you don't need the list
Swap the brackets for parentheses and Python produces items lazily, one at a time, instead of building the whole list:
total = sum(n * n for n in nums)
print(total) # 91
g = (n * n for n in nums)
print(type(g).__name__) # generator
When a generator expression is the only argument to a function, the extra parentheses can be dropped, as in sum(...) above. The memory difference is large. Measured with sys.getsizeof for one million integers:
import sys
print(sys.getsizeof([n for n in range(1_000_000)])) # 8448728
print(sys.getsizeof(n for n in range(1_000_000))) # 192
That is about 8.4 MB for the list object (not counting the integers themselves) versus 192 bytes for the generator. If you only loop over the results once, or pass them to sum(), any(), max() or "".join(), use a generator.
Scope: the loop variable doesn't leak
In Python 3, a comprehension runs in its own scope. The language reference says this "ensures that names assigned to in the target list don't 'leak' into the enclosing scope":
x = "outer"
r = [x for x in range(3)]
print(x) # outer
One detail matters when you reference variables: the iterable in the first for clause is evaluated in the enclosing scope, everything else inside the comprehension's own scope. Python 3.12 changed how this is implemented (PEP 709 inlines list, dict and set comprehensions instead of creating a hidden function), which makes them faster but keeps the scoping behaviour. One visible side effect: a comprehension no longer gets its own frame in tracebacks.
If you do want to keep a value computed inside a filter, the walrus operator works:
big = [y for n in nums if (y := n * 10) > 30]
print(big) # [40, 50, 60]
Is a list comprehension faster than a for loop?
Usually a little. Doubling 1,000 numbers, measured with python -m timeit on Python 3.12.2 on Windows:
| Method | Time per run (best of 5) |
|---|---|
[n*2 for n in nums] | 23 µs |
for loop with r.append(n*2) | 35.3 µs |
list(map(lambda n: n*2, nums)) | 55.6 µs |
Your numbers will differ by machine, but the ranking is typical: the loop pays for looking up and calling append each time, and map with a lambda pays for a function call per item. Reproduce it with:
python -m timeit -s "nums=list(range(1000))" "[n*2 for n in nums]"
python -m timeit -s "nums=list(range(1000))" "r=[]" "for n in nums: r.append(n*2)"
When a for loop is the better choice
- Side effects. Don't write
[print(x) for x in items]. It builds a throwaway list ofNonevalues. Use a loop. - More than two clauses, or more than one line. If you need to break the comprehension across several lines to read it, a loop with named steps is usually clearer.
- Error handling. You can't put
try/exceptinside a comprehension. Move the risky part into a small function and call that from the comprehension, or use a loop. - Early exit. Comprehensions always process the whole iterable. If you need to stop at the first match, use
next(x for x in items if test(x))or a loop withbreak.
If an error is raised inside a comprehension, the traceback points at the comprehension's line; how to read a stack trace explains how to find the failing item.
Frequently asked questions
- Are list comprehensions faster than for loops?
- Usually somewhat faster for building a list, because they avoid repeated lookups of the append method. In a timeit test on Python 3.12, doubling 1,000 numbers took 23 microseconds with a comprehension and 35.3 microseconds with a loop and append. The difference only matters in hot code; choose whichever is clearer.
- Can a list comprehension have elif?
- Not directly, but you can chain conditional expressions: ["neg" if n < 0 else "zero" if n == 0 else "pos" for n in nums]. Once it needs more than one else, a regular function called from the comprehension, or a plain for loop, is easier to read.
- What is the difference between a list comprehension and a generator expression?
- Square brackets build the whole list in memory at once. Parentheses create a generator that produces one item at a time as it is consumed. For a million integers, the list took about 8.4 MB in a test on Python 3.12, while the generator object took 192 bytes. Use a generator when you only need to loop over the results once, for example inside sum().
- Does the loop variable leak out of a list comprehension?
- Not in Python 3. A comprehension runs in its own scope, so a variable named x outside it keeps its value. The language reference describes this as keeping names assigned in the loop from leaking into the enclosing scope.