Python list comprehensions: examples and traps
Published
By the Unrust team · 12 min read · Editorial method
How Python list comprehensions work: if and if-else, nested loops, dict and set forms, timings vs a for loop, four traps and when a loop is clearer.
Open the free companion tool →What is a list comprehension in Python?
A Python list comprehension builds a new list in one expression: [expression for item in iterable if condition]. It matches a for loop that appends to a list, ran 10 to 35% faster in our Python 3.11 and 3.13 timings, and is the idiomatic choice when the body is one transform or filter with no side effects.
Read it in three parts. The expression on the left is what goes into the new list. The for clause names the loop variable and the iterable it walks. The optional if clause, at the end, decides which items get through. Every example in this article was run with CPython 3.11.2 and 3.13.15 on November 13, 2026, and the printed output is shown in the comments.
# [ expression for item in iterable if condition ]
# ^ what to keep ^ the loop ^ optional filter
squares = [n * n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# The same result as a for loop
result = []
for n in range(5):
result.append(n * n)
print(result == squares) # TrueList comprehension vs for loop: the equivalence table
Every list comprehension can be rewritten as a for loop that appends to an empty list, and the clauses keep their order when you do. The for and if clauses become nested statements from left to right, and the leading expression becomes the append argument in the innermost block. That one rule is enough to translate, and to trace, any comprehension.
The table below pairs common loop shapes with their comprehension form and says which one to prefer. The right-hand column matters most: a comprehension is a good fit only while the loop body stays a single expression.
Task for loop body Comprehension Prefer
----------------------- ------------------------------------ ------------------------------------- ----------------------
Transform each item out.append(f(x)) [f(x) for x in xs] Comprehension
Filter items if ok(x): out.append(x) [x for x in xs if ok(x)] Comprehension
Transform or fall back out.append(a if c else b) [a if c else b for x in xs] Comprehension
Flatten one level for row in m: for x in row: append [x for row in m for x in row] Comprehension
Build a dict d[k(x)] = v(x) {k(x): v(x) for x in xs} Dict comprehension
Unique values s.add(f(x)) {f(x) for x in xs} Set comprehension
Aggregate once total += x sum(x for x in xs) Generator expression
Print, write or log print(x) (none) for loop
Handle exceptions try: ... except: ... (none, without a helper) for loop
Break early if done: break (none) for loop or next()Is a list comprehension faster than a for loop?
Yes, usually by a modest margin. Doubling 10,000 integers took 250 microseconds as a comprehension against 372 microseconds as an append loop on Python 3.13.15, and 211 against 234 microseconds on Python 3.11.2. Filtering the same list to multiples of 3 took 317 against 473 microseconds on 3.13 and 288 against 300 on 3.11. Each figure is the best of seven timeit runs of 1,000 loops on one shared Linux machine, so treat the ratios as indicative, not as a benchmark of your hardware.
Much of the gap comes from the loop version looking up and calling out.append on every iteration, which the comprehension avoids. Python 3.12 also inlined list, dict and set comprehensions (PEP 709), which the release notes say speeds up a comprehension by up to two times by no longer creating a function object each time it runs. map with a lambda was the slowest option in both versions, at 543 and 393 microseconds, because it still pays for a Python function call per item.
Speed is rarely the reason to choose one. A saving of about 100 microseconds per 10,000 items will not matter next to a database query. Choose the form a reviewer can check fastest, then measure if the loop is genuinely hot.
import timeit
setup = "data = list(range(10_000))"
loop = """
out = []
for n in data:
out.append(n * 2)
"""
comp = "out = [n * 2 for n in data]"
for name, stmt in [("loop", loop), ("comprehension", comp)]:
best = min(timeit.repeat(stmt, setup, number=1000, repeat=7))
print(name, round(best / 1000 * 1e6, 1), "microseconds")
# Python 3.13.15: loop 372.0, comprehension 249.7
# Python 3.11.2: loop 234.3, comprehension 210.5How to use if and if-else in a list comprehension
A trailing if filters items, and an if-else before the for chooses a value for every item. The position is the whole difference. [n for n in xs if n > 0] drops the non-positive numbers, so the result can be shorter than the input. [n if n > 0 else 0 for n in xs] keeps every position and replaces the non-positive ones, so the result is always the same length.
Writing [n for n in xs if n > 0 else 0] is a SyntaxError, because a filter has nothing to put in the list when it fails. If you want a fallback value, you want the conditional expression at the front. You can combine both: the conditional expression shapes each surviving item and the trailing if decides which items survive.
readings = [-2, 5, -1, 3]
print([n for n in readings if n > 0]) # [5, 3] filter: shorter list
print([n if n > 0 else 0 for n in readings]) # [0, 5, 0, 3] conditional: same length
words = ["Apple", "kiwi", "Banana", "fig"]
print([w.lower() for w in words if len(w) > 4]) # ['apple', 'banana']
print([w if len(w) > 4 else "-" for w in words]) # ['Apple', '-', 'Banana', '-']Nested list comprehensions: flatten a 2D list and read the loop order
To flatten a list of lists, write the for clauses in the same order you would nest the loops: [x for row in grid for x in row]. The leftmost for is the outer loop. Beginners often guess the reverse because the expression x appears first, but the expression is evaluated last, inside the innermost loop.
A list comprehension inside the expression is different: it builds one inner list per outer item. [[row[i] for row in matrix] for i in range(3)] transposes a 2 by 3 matrix into a 3 by 2 one. When you trace either form, write it out as the nested for loops it stands for and keep one row per innermost iteration, as in a trace table. Unrust's trace table examples post (/blog/trace-table-examples) shows the column layout, and the Python code tracing practice page (/languages/python/code-tracing) has more drills.
Two for clauses is usually the readable limit. With three, or with an if attached to the inner loop, the nested loop version is easier to review.
grid = [[1, 2, 3], [4, 5], [6]]
print([x for row in grid for x in row]) # [1, 2, 3, 4, 5, 6]
# Same order as:
# for row in grid:
# for x in row:
# out.append(x)
print([(r, c) for r in range(2) for c in "ab"])
# [(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')] the right-hand loop varies fastest
matrix = [[1, 2, 3], [4, 5, 6]]
print([[row[i] for row in matrix] for i in range(3)]) # [[1, 4], [2, 5], [3, 6]]List comprehension vs generator expression vs map and filter
A list comprehension builds the whole list immediately; a generator expression, written with parentheses, produces items lazily and can be consumed only once. For 100,000 squares, sys.getsizeof reported 800,984 bytes for the list (its pointer array alone) and about 200 bytes for the generator object on both Python versions. If you only feed the values to sum, any, max or a single for loop, pass a generator expression: sum(n * n for n in range(100_000)).
The cost of laziness is that a generator is exhausted after one pass. A second comprehension over the same generator silently returns an empty list, with no exception. Unrust's post on exhausted iterators and mutable defaults (/blog/python-exhausted-iterators-and-mutable-defaults) traces this bug, and the free Python iterator explorer lets you step through a partially consumed generator.
map and filter are equally valid and are lazy in Python 3. They read well when you already have a named function, as in map(str.upper, names). When you would need a lambda, the comprehension is usually shorter and, in our timings, faster.
import sys
as_list = [n * n for n in range(100_000)]
as_gen = (n * n for n in range(100_000))
print(sys.getsizeof(as_list), sys.getsizeof(as_gen))
# 800984 200 on 3.13.15 (208 on 3.11.2)
print(sum(n * n for n in range(100_000))) # 333328333350000
evens = (n for n in range(6) if n % 2 == 0)
print([n for n in evens], [n for n in evens]) # [0, 2, 4] []
print(list(map(str.upper, ["a", "b"]))) # ['A', 'B']Dict and set comprehensions, and how to list 1 to 100 in Python
The same syntax builds dictionaries and sets: {key: value for item in iterable} makes a dict and {expression for item in iterable} makes a set. With a dict comprehension, a repeated key keeps the last value written, and a set comprehension drops duplicates, so both can return fewer entries than the input had.
To list the numbers 1 to 100, use list(range(1, 101)). The stop value is excluded, so 101 is needed to include 100. [i for i in range(1, 101)] gives an identical list, but a comprehension that only copies items adds nothing over list(), and linters such as Ruff flag it as unnecessary.
names = ["ada", "grace", "linus", "ada"]
print({n: len(n) for n in names}) # {'ada': 3, 'grace': 5, 'linus': 5}
print({len(n) for n in names}) # {3, 5}
numbers = list(range(1, 101))
print(numbers[0], numbers[-1], len(numbers)) # 1 100 100
print([i for i in range(1, 101)] == numbers) # True, but list() is clearerFour list comprehension traps that pass code review
Late binding: [lambda: i for i in range(3)] creates three functions that all look up i when they are called, after the loop has finished, so every one returns 2. Bind the current value with a default argument, lambda i=i: i, or use functools.partial.
Scope: in Python 3 the loop variable stays inside the comprehension, so x = 'outer' followed by [x * 2 for x in range(3)] leaves x as 'outer'. Python 2 leaked it. Python 3.12 inlining did not change this; the release notes say iteration variables remain isolated.
Walrus: an assignment expression such as (y := r * 10) inside a comprehension binds y in the enclosing scope, so y still exists after the comprehension ends, holding the last value computed. That is useful for reusing a computed value in the filter, and surprising if a later line reads y.
Side effects: [seen.append(n) for n in items] works, but it builds a throwaway list of None values just to run append. If you are discarding the result, write a for loop.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
x = "outer"
doubled = [x * 2 for x in range(3)]
print(x, doubled) # outer [0, 2, 4]
readings = [3, 9, 4, 12]
print([y for r in readings if (y := r * 10) > 50]) # [90, 120]
print(y) # 120, leaked on purpose
seen = []
junk = [seen.append(n) for n in range(3)]
print(junk, seen) # [None, None, None] [0, 1, 2]When a for loop is clearer than a list comprehension
Use a for loop when any item on this checklist is true: the body has a side effect such as printing, writing or mutating something else; you need try and except around part of the work; you need break or continue with a reason a reviewer should see; there are more than two for clauses; the condition needs a comment to explain it; or you are discarding the resulting list.
The example below parses counts from raw rows and reports bad ones. The loop is longer, but each rule has its own line. The one-line version needs a helper function and a walrus to stay correct, and it quietly drops the warning. That trade-off is what Unrust's idiomatic code guide (/guides/idiomatic-code) means by idiomatic: the form a reader of this codebase can verify fastest, not the shortest form.
rows = ["3", "x", "7", "", "12"]
def parse_counts(rows):
counts = []
for raw in rows:
if not raw:
continue # blank rows are expected
try:
counts.append(int(raw))
except ValueError:
print(f"skipping {raw!r}") # bad rows are reported
return counts
print(parse_counts(rows)) # skipping 'x' then [3, 7, 12]
# The comprehension needs a helper and a walrus, and loses the warning
def to_int(raw):
try:
return int(raw)
except ValueError:
return None
print([n for raw in rows if raw and (n := to_int(raw)) is not None]) # [3, 7, 12]Predict the output: nested clause order
Write the two for clauses out as nested loops before you reveal the answer. Which pairs does this print, and in what order?
pairs = [(a, b) for a in range(3) for b in range(a)]
print(pairs)Reveal the answer and explanation
It prints [(1, 0), (2, 0), (2, 1)]. The outer loop is a and the inner loop is b, so the inner range depends on the current a. When a is 0, range(0) is empty and nothing is added. When a is 1, b takes only 0. When a is 2, b takes 0 and then 1.
If you predicted pairs starting with (0, ...), you probably read the clauses right to left or forgot that range(0) produces no items.
Predict the output: lambdas built in a comprehension
Each lambda multiplies n by 10. What does the last line print?
fns = [lambda: n * 10 for n in [1, 2, 3]]
print([f() for f in fns])Reveal the answer and explanation
It prints [30, 30, 30]. The lambdas do not store n when they are created; they look it up when they are called. By then the comprehension has finished and n is 3 in its scope, so all three return 30.
Binding the value at creation time with a default argument fixes it and prints [10, 20, 30].
fns = [lambda n=n: n * 10 for n in [1, 2, 3]]
print([f() for f in fns]) # [10, 20, 30]Predict the output: two comprehensions over one iterator
nums is an iterator, not a list. What are odds and evens?
nums = iter([1, 2, 3, 4])
odds = [n for n in nums if n % 2]
evens = [n for n in nums if n % 2 == 0]
print(odds, evens)Reveal the answer and explanation
It prints [1, 3] []. The first comprehension consumes all four items, keeping 1 and 3. The second comprehension starts from an exhausted iterator, so it finds nothing and returns an empty list without raising an error.
Convert the input to a list once, before either pass, so both comprehensions read the same values.
nums = list(iter([1, 2, 3, 4]))
odds = [n for n in nums if n % 2]
evens = [n for n in nums if n % 2 == 0]
print(odds, evens) # [1, 3] [2, 4]Predict the output: a filter and a conditional together
This comprehension has both a conditional expression and a trailing filter. Which one runs first, and what is printed?
labels = ["a", "", "b"]
print([x if x else "empty" for x in labels if x != "b"])Reveal the answer and explanation
It prints ['a', 'empty']. The trailing filter runs first for each item and removes 'b'. Only the surviving items reach the conditional expression, which turns the empty string into 'empty' and keeps 'a' unchanged.
Python list comprehensions: FAQ
Is a list comprehension better than a for loop? It is better when the loop only builds a list with one transform or filter: it is shorter, states its intent in one line and ran 10 to 35% faster in our tests. A for loop is better when the body has side effects, needs exception handling or break, or would need more than two for clauses.
Can you use elif in a list comprehension? Not directly. You can chain conditional expressions, as in ['neg' if n < 0 else 'zero' if n == 0 else 'pos' for n in xs], but past two branches a small named function or a loop is easier to read.
Are list comprehensions Pythonic? Yes, for building lists. PEP 202 added them to Python 2.0 as a more concise way to create lists where map, filter and nested loops would otherwise be used. Using one only for its side effects, or nesting three levels deep, is not considered Pythonic.
What is the difference between a list comprehension and a generator expression? Square brackets build the full list in memory at once; parentheses create a lazy generator that yields one item at a time and can be iterated only once. Use the generator when you consume the values a single time, for example inside sum or any.
Does a list comprehension variable leak into the outer scope? Not in Python 3: the loop variable is local to the comprehension. The exception is an assignment expression with :=, which deliberately binds its name in the enclosing scope.
Practise reading comprehensions without running them
Knowing the syntax is the easy half. The skill that pays off in review is predicting what a comprehension produces before you run it: the clause order, what the filter drops, and whether the input can be read twice. Unrust's Python idiomatic code practice (/languages/python/idiomatic-code) and Python code tracing practice (/languages/python/code-tracing) drill exactly that, with AI help and hints switched off.
References and next steps
- Python Tutorial: List comprehensions
- Python Language Reference: Displays for lists, sets and dictionaries
- What's New in Python 3.12: PEP 709, comprehension inlining
- PEP 202: List Comprehensions
- PEP 572: Assignment Expressions
- Python FAQ: why do lambdas defined in a loop all return the same result?
- Practise writing idiomatic Python
- Experiment with the companion tool
Predict Python output against the clock
Take Unrust's free diagnostic in Python with AI and hints closed: about 14 minutes. Idiom / Quality is one of six skills it samples, alongside recall, tracing, comprehension, debugging and AI-slop detection.
More from the blog
- Python debugging exercises: 10 bugs to fix
Python · 16 min read
- Idiomatic Python: 10 patterns with examples
Python · 15 min read
- Can't code without AI? A 4-week recovery plan
AI & coding skills · 10 min read