list comprehension
A list comprehension builds a new list from another collection in one readable line, with an optional filter to keep only some items.
[expression for item in iterable]
[expression for item in iterable if condition]A list comprehension is a short way to write "make a new list by doing something to every item". [x * 2 for x in numbers] gives a list with every number doubled.
Add if at the end to keep only some items: [x for x in numbers if x > 0]. Put a conditional expression at the front to change items in two different ways: [x if x > 0 else 0 for x in numbers].
It does the same job as a for loop loop with append(), but in one line and usually a little faster. When the logic gets long or needs several steps, go back to a normal loop: readable beats short.
Return value
A new list. The original collection does not change.
Examples
1Transform every item
prices = [10, 25, 40]
with_vat = [p * 1.2 for p in prices]
print(with_vat)
names = ["ana", "omar", "li"]
print([n.title() for n in names])[12.0, 30.0, 48.0] ['Ana', 'Omar', 'Li']
2Keep only some items
temps = [18, 25, 31, 22, 35]
hot = [t for t in temps if t >= 30]
print(hot)[31, 35]
3Same thing as a for loop
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares)
print([n * n for n in range(1, 6)])[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
4if / else at the front
scores = [72, 45, 90, 58]
results = ["pass" if s >= 60 else "fail" for s in scores]
print(results)['pass', 'fail', 'pass', 'fail']
A filter if goes at the end; a choose-between-two if ... else goes at the front.
5Clean up a CSV line
line = " Berlin , Paris,, Rome ,Oslo "
cities = [c.strip() for c in line.split(",") if c.strip()]
print(cities)['Berlin', 'Paris', 'Rome', 'Oslo']
Common mistakes
Putting else at the end
[x for x in nums if x > 0 else 0] is a SyntaxError. A filter cannot have else. Move the choice to the front: [x if x > 0 else 0 for x in nums].
nums = [3, -1, 5]
print([x if x > 0 else 0 for x in nums])[3, 0, 5]
Using a comprehension only for side effects
[print(x) for x in items] works but builds a useless list of Nones. Use a normal for loop when you are not keeping the result.
Cramming too much into one line
Two nested loops plus a condition in one comprehension is hard to read. Split it into a normal loop or a small function.
Questions people ask
Can I use two for clauses?
Yes, they run like nested loops, left to right: [(r, c) for r in range(2) for c in range(3)].
How do I make a dictionary or set the same way?
Use curly braces: dict comprehension {k: v for ...}, or a set comprehension {x for ...}.
What about round brackets?
(x * 2 for x in nums) is a generator expression: it produces values one at a time instead of building a list. Great inside sum() or max().
Is a list comprehension faster than a for loop?
Usually a bit, because it avoids calling append() each time. But choose it for clarity, not speed.