Engineering
Python List Comprehensions: A Practical Tutorial with Examples
Learn Python list comprehensions step by step: syntax, filters, if-else, nesting, dict and set comprehensions, generator expressions and readability tips.
By Japan Gor · · 7 min read
List comprehensions are one of the first features that make Python code feel "Pythonic". They let you build a new list from an existing iterable in a single readable expression, replacing a loop, an empty list and repeated append() calls. This tutorial covers the syntax from the ground up, adds conditions and nesting, introduces the closely related dictionary, set and generator forms, and finishes with honest advice on readability and performance. Every example runs as-is on Python 3.
The basic syntax
Here's a typical loop that squares numbers:
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]
The equivalent list comprehension:
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
print(squares) # [1, 4, 9, 16, 25]
Read it left to right as: "a list of n * n, for each n in numbers". The general shape is:
[expression for item in iterable]
- expression – what goes into the new list (any valid expression).
- item – the loop variable.
- iterable – anything you can loop over: a list, tuple, string,
range(), file, dictionary and so on.
The official Python tutorial on list comprehensions describes them as a concise way to create lists, and the formal grammar is in the language reference on displays. The feature was introduced by PEP 202.
More basic examples
words = ["apple", "Banana", "cherry"]
print([w.upper() for w in words]) # ['APPLE', 'BANANA', 'CHERRY']
print([len(w) for w in words]) # [5, 6, 6]
print([c for c in "hello"]) # ['h', 'e', 'l', 'l', 'o']
print([i * 10 for i in range(4)]) # [0, 10, 20, 30]
prices = {"tea": 20, "coffee": 35}
print([f"{k}: Rs {v}" for k, v in prices.items()])
# ['tea: Rs 20', 'coffee: Rs 35']
Note the last example: you can unpack tuples in the for clause just like a normal loop.
Filtering with if
Add an if clause at the end to keep only some items:
numbers = range(1, 11)
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
names = ["Asha", "", "Ravi", None, "Meera"]
clean = [n for n in names if n]
print(clean) # ['Asha', 'Ravi', 'Meera']
The filter runs before the expression, so items that fail the test are never transformed. You can chain several conditions with and/or, or even write multiple if clauses (they combine like and):
print([n for n in range(30) if n % 2 == 0 if n % 3 == 0])
# [0, 6, 12, 18, 24]
Transforming with if ... else
A common point of confusion: if you want to choose a value for every item rather than drop items, use a conditional expression in the expression position, before for:
numbers = [1, 2, 3, 4, 5]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd']
| Goal | Where the condition goes | Example |
|---|---|---|
| Keep some items | After the for | [x for x in xs if x > 0] |
| Choose a value per item | Before the for | [x if x > 0 else 0 for x in xs] |
Writing [x for x in xs if x > 0 else 0] is a SyntaxError, because a trailing if filter can't have an else.
Nested comprehensions
Multiple for clauses
Multiple for clauses are evaluated in the same order as nested loops written top to bottom:
pairs = [(x, y) for x in [1, 2, 3] for y in ["a", "b"]]
print(pairs)
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
That's equivalent to:
pairs = []
for x in [1, 2, 3]:
for y in ["a", "b"]:
pairs.append((x, y))
A practical use is flattening a list of lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
A comprehension inside a comprehension
Putting a comprehension in the expression position builds nested lists. Transposing a matrix is the classic example from the Python docs:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
For this particular job, the built-in zip() is simpler: [list(col) for col in zip(*matrix)].
Dictionary and set comprehensions
The same idea works for dictionaries and sets, using curly braces.
Dict comprehensions
words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}
prices = {"tea": 20, "coffee": 35, "juice": 60}
affordable = {k: v for k, v in prices.items() if v <= 40}
print(affordable) # {'tea': 20, 'coffee': 35}
inverted = {v: k for k, v in prices.items()}
print(inverted) # {20: 'tea', 35: 'coffee', 60: 'juice'}
When inverting, watch out for duplicate values: later keys silently overwrite earlier ones.
Set comprehensions
emails = ["[email protected]", "[email protected]", "[email protected]"]
domains = {e.split("@")[1] for e in emails}
print(sorted(domains)) # ['x.com', 'y.com']
Sets remove duplicates automatically and have no guaranteed order, which is why the example sorts before printing.
Generator expressions
Replace the square brackets with parentheses and you get a generator expression, which produces items lazily, one at a time, instead of building the whole list in memory (PEP 289):
total = sum(n * n for n in range(1_000_000))
print(total) # 333332833333500000
When a generator expression is the only argument to a function, you can drop the extra parentheses, as above. Use generators when:
- You'll consume the values once (summing,
any(),all(),max(), writing to a file). - The data is large or comes from a stream like a file.
lines = ["ok", "ERROR: disk", "ok", "ERROR: net"]
has_errors = any(line.startswith("ERROR") for line in lines)
print(has_errors) # True
any() stops as soon as it finds a match, so a generator avoids doing unnecessary work. Note that a generator can only be iterated once; convert it with list() if you need to reuse the results.
Scope: the loop variable doesn't leak
In Python 3, the loop variable in a comprehension has its own scope and doesn't overwrite a variable with the same name outside it:
x = "outside"
result = [x for x in range(3)]
print(x) # outside
This differs from a regular for loop, where the loop variable remains defined after the loop. The assignment expression (:=, the "walrus" operator) is an exception: a target assigned with := inside a comprehension binds in the containing scope.
Readability guidelines
Comprehensions are great until they aren't. Some practical rules:
- One transformation and one filter is the sweet spot. If you're writing three
forclauses with conditions, use a regular loop. - Don't use comprehensions for side effects.
[print(x) for x in xs]builds a useless list ofNonevalues. Use aforloop. - Name things. If the expression is complex, move it into a small function:
[normalise(name) for name in names]. - Split long comprehensions across lines inside the brackets:
active_emails = [
user["email"].lower()
for user in [{"email": "[email protected]", "active": True}, {"email": "[email protected]", "active": False}]
if user["active"]
]
print(active_emails) # ['[email protected]']
Performance notes
List comprehensions are often somewhat faster than the equivalent for loop with append(), mainly because they avoid repeatedly looking up and calling the append method. In CPython 3.12, PEP 709 inlined list, dict and set comprehensions, which removed some of their call overhead. The exact difference depends on your Python version and the work done per item, and when the expression itself is expensive (a network call, a regex, a database query), the loop overhead becomes irrelevant.
If speed matters, measure it on your own code with the standard library's timeit module rather than relying on general claims:
import timeit
loop = """
out = []
for n in range(1000):
out.append(n * n)
"""
comp = "out = [n * n for n in range(1000)]"
print("loop:", timeit.timeit(loop, number=2000))
print("comp:", timeit.timeit(comp, number=2000))
For memory, prefer a generator expression when you don't need the whole list at once.
Quick reference
[expr for x in xs] # map
[x for x in xs if cond] # filter
[a if cond else b for x in xs] # choose value per item
[expr for x in xs for y in ys] # nested loops / flatten
{k: v for k, v in pairs} # dict comprehension
{expr for x in xs} # set comprehension
(expr for x in xs) # generator expression
Summary
A list comprehension is a compact, readable way to build a list by transforming and filtering an iterable. Put filters after the for, conditional values before it, read multiple for clauses as nested loops, use curly braces for dicts and sets, and switch to a generator expression when you only need to iterate once. Keep them short, avoid side effects, and fall back to a plain loop the moment a comprehension stops being easy to read.