Python course menu
Python Comprehensions: List, Dict and Set Comprehensions Explained
Learn Python comprehensions: build lists in one line, filter with if, transform with if-else, dictionary and set comprehensions, nested comprehensions and flattening, generator expressions with sum/any/all, and when a loop is clearer.
On this page
A comprehension builds a new list, dictionary or set from an existing iterable in a single, readable line. It replaces the common pattern of "create an empty list, loop, append".
From loop to comprehension#
result = []
for n in range(1, 6):
if n % 2:
result.append(n * 10)
print(result, [n * 10 for n in range(1, 6) if n % 2])[10, 30, 50] [10, 30, 50]Both produce the same list. Read the comprehension as: "n * 10 for each n in range(1, 6), if n is odd".
List comprehensions#
The general form is:
[expression for item in iterable if condition]squares = [n * n for n in range(1, 6)]
print(squares)[1, 4, 9, 16, 25]Filtering with if#
An if at the end keeps only some items:
nums = [4, -2, 7, 0, -5, 9]
print([n for n in nums if n > 0])[4, 7, 9]Transforming with if-else#
A conditional expression at the start changes each item but keeps them all:
print([n if n > 0 else 0 for n in nums])[4, 0, 7, 0, 0, 9]Methods work as usual inside the expression:
words = ["Python", "SQL", "Go", "JavaScript"]
print([w.lower() for w in words if len(w) > 2])['python', 'sql', 'javascript']Dictionary comprehensions#
Use key: value inside curly braces:
prices = {"tea": 20, "coffee": 35, "juice": 50}
with_tax = {item: round(p * 1.18, 2) for item, p in prices.items()}
print(with_tax)
cheap = {k: v for k, v in prices.items() if v < 40}
print(cheap)
inverted = {v: k for k, v in prices.items()}
print(inverted){'tea': 23.6, 'coffee': 41.3, 'juice': 59.0}
{'tea': 20, 'coffee': 35}
{20: 'tea', 35: 'coffee', 50: 'juice'}Set comprehensions#
Curly braces without a colon build a set, so duplicates disappear:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
print(sorted({w[0] for w in words}))
print(sorted({len(w) for w in words}))['a', 'b', 'c']
[5, 6, 7, 9](Sets have no order, so they are sorted here for display.)
Nested comprehensions#
Several for clauses read left to right, like nested loops. Flattening a list of lists:
matrix = [[1, 2, 3], [4, 5, 6]]
print([n for row in matrix for n in row])
print([[row[i] for row in matrix] for i in range(3)]) # transpose
print([(x, y) for x in "ab" for y in (1, 2)])[1, 2, 3, 4, 5, 6]
[[1, 4], [2, 5], [3, 6]]
[('a', 1), ('a', 2), ('b', 1), ('b', 2)][n for row in matrix for n in row] is the same as:
for row in matrix:
for n in row:
...Generator expressions with sum, any and all#
Parentheses instead of brackets give a lazy generator expression. They pair perfectly with functions that consume values:
total = sum(n * n for n in range(1, 11))
print(total, any(n > 90 for n in [40, 95]), all(n > 0 for n in [3, 0]))385 True FalseWhen to use a loop instead#
Comprehensions are for building a collection. Prefer a normal loop when:
- the logic needs several statements,
try/except, orprints; - there are more than two
forclauses or complex conditions; - you are not building a collection at all (for example, only printing or saving).
A comprehension that needs a minute to understand has lost its advantage.
Common mistakes#
Practice#
Practice exercise
Given this list of students, build (1) a list of the names of those who passed (score ≥ 40) and (2) a dictionary mapping every name to a grade: "A" for 90+, "B" for 50+, otherwise "F".
students = [{"name": "Asha", "score": 92}, {"name": "Ravi", "score": 58},
{"name": "Meera", "score": 97}, {"name": "John", "score": 34}]Show hint
The list needs a filter at the end. The dictionary needs a chained conditional expression in the value: "A" if ... else "B" if ... else "F".
Show solution
passed = [s["name"] for s in students if s["score"] >= 40]
grades = {s["name"]: ("A" if s["score"] >= 90 else "B" if s["score"] >= 50 else "F")
for s in students}
print(passed)
print(grades)['Asha', 'Ravi', 'Meera']
{'Asha': 'A', 'Ravi': 'B', 'Meera': 'A', 'John': 'F'}Key takeaway#
Finished this lesson?