Python list comprehensions explained, with examples
8 min read
A list comprehension builds a new list from an existing one in a single line. It's one of the first things that makes Python code look “Pythonic”, and once it clicks you'll use it every day.
The shape is always the same:
[expression for item in items]
Read it as: “work out expression for each item in items, and collect the results in a list.”
From a loop to a comprehension
Say you have some prices and want them with 20% tax added. With a loop:
prices = [4.0, 12.5, 7.25]
with_tax = []
for p in prices:
with_tax.append(round(p * 1.2, 2))
print(with_tax) # [4.8, 15.0, 8.7]The same thing as a list comprehension:
prices = [4.0, 12.5, 7.25]
with_tax = [round(p * 1.2, 2) for p in prices]
print(with_tax) # [4.8, 15.0, 8.7]Everything the loop did is still there. The for p in prices part is the loop, and round(p * 1.2, 2) is what used to go inside append(). The empty list and the append are gone because the comprehension handles them for you.
Another example, capitalizing names:
names = ["ada", "grace", "alan"]
print([name.title() for name in names]) # ['Ada', 'Grace', 'Alan']Filtering with if
Add an if at the end to keep only some items:
scores = [72, 45, 88, 50, 31]
passed = [s for s in scores if s >= 50]
print(passed) # [72, 88, 50]You can filter and transform at once. This keeps words longer than two letters and lower-cases them:
words = ["Python", "is", "easy", "to", "read"]
print([w.lower() for w in words if len(w) > 2]) # ['python', 'easy', 'read']Choosing a value with if/else
What if you don't want to drop items, but label each one? Then the if ... else goes at the start, as part of the expression:
scores = [72, 45, 88, 50, 31]
labels = ["pass" if s >= 50 else "fail" for s in scores]
print(labels) # ['pass', 'fail', 'pass', 'pass', 'fail']This is the part that confuses most beginners, so it's worth remembering:
Where the if goes | What it does | Length of the new list |
|---|---|---|
At the end: [s for s in scores if s >= 50] | Filters: drops items that fail the test | Can be shorter |
At the start, with else: ["pass" if s >= 50 else "fail" for s in scores] | Picks a value for every item | Always the same |
Putting if ... else at the end, like ["pass" for s in scores if s >= 50 else "fail"], is a SyntaxError.
Two for clauses: flattening a list of lists
A comprehension can contain more than one for. They run in the same order as nested loops, outer loop first:
rows = [[1, 2], [3], [4, 5]]
flat = [n for row in rows for n in row]
print(flat) # [1, 2, 3, 4, 5]It does exactly what this does:
rows = [[1, 2], [3], [4, 5]]
flat = []
for row in rows:
for n in row:
flat.append(n)
print(flat) # [1, 2, 3, 4, 5]If the order ever feels backwards, write the nested loops first, then copy the for lines across in the same order.
Building a grid (and a common bug)
To make a 2 by 3 grid of zeros, use a comprehension:
grid = [[0] * 3 for _ in range(2)]
print(grid) # [[0, 0, 0], [0, 0, 0]]The shortcut [[0] * 3] * 2 looks the same when printed, but both rows are the same list in memory. Change grid[0][0] and grid[1][0] changes too. The comprehension creates a new row each time, so the rows are independent. The _ is a common name for a loop variable you don't use.
Dictionary and set comprehensions
The same idea works with curly braces. A dictionary comprehension uses key: value:
names = ["ada", "grace", "alan"]
lengths = {name: len(name) for name in names}
print(lengths) # {'ada': 3, 'grace': 5, 'alan': 4}Without the colon you get a set, which keeps only unique values:
names = ["ada", "grace", "alan"]
print({len(name) for name in names}) # {3, 4, 5}And if you only need a total, drop the brackets and pass it straight to a function like sum():
scores = [72, 45, 88, 50, 31]
print(sum(s for s in scores if s >= 50)) # 210That last one is a generator expression. It works out values one at a time instead of building a whole list, which saves memory on large data.
When to use a loop instead
Comprehensions are for building a new list. Use a regular loop when:
- You're doing something, not building something, like printing or saving to a file.
[print(n) for n in numbers]works but builds a useless list ofNones. - The logic needs more than one line, or several conditions. If you have to read a comprehension twice, a loop is clearer.
- You'd nest a comprehension inside another one.
[[row[i] for row in matrix] for i in range(3)]swaps the rows and columns of a matrix, but most readers have to stop and decode it.
A good rule: if it fits comfortably on one line and reads like a sentence, use a comprehension. Otherwise, write the loop.
Comprehensions vs map() and filter()
Python also has map() and filter(), which do the same jobs:
names = ["ada", "grace", "alan"]
scores = [72, 45, 88, 50, 31]
print(list(map(str.upper, names))) # ['ADA', 'GRACE', 'ALAN']
print(list(filter(lambda s: s >= 50, scores))) # [72, 88, 50]Both are fine, and you'll see both in real code. Most Python developers find comprehensions easier to read, especially once a lambda is involved.
Practice
Try these. Each one is a single line:
- Square every number in
[1, 2, 3, 4]. - Keep only the even numbers from
range(20). - Turn
["apple", "kiwi", "banana"]into a list of their first letters. - Make a dictionary mapping each word in
"the quick brown fox"to its length.
Learn this with hands-on practice. List comprehensions, map(), filter() and reduce() are covered in the Map, Filter, Reduce & Files module of Blackprint's Intro to Python, with coding challenges that check your code as you go. See the course