Comprehensions
Build a new list, set or dictionary in a single, readable line — the most Pythonic idiom there is.
What you will learn
- Write a list comprehension
- Add a condition (filter) inside one
- Use dict and set comprehensions
The long way first
A very common task is building a new list from an old one — for example, the squares of some numbers. The plain way is a loop with .append():
numbers = [1, 2, 3, 4]
squares = []
for n in numbers:
squares.append(n * n)
print(squares)This works fine: we start with an empty list squares, loop over each number n, and append n * n each time. After the loop, squares holds the four squared values. But it took four lines to express one simple idea.
Note: Output: [1, 4, 9, 16]
A comprehension does it in one line
A list comprehension is a compact way to write that exact loop inside the square brackets. It reads almost like English: “give me n * n for each n in numbers.”
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers]
print(squares)Read the part inside the brackets left to right: n * n is what to collect, and for n in numbers is where the values come from. Python runs the loop for you, squares each number, and gathers the results into a brand-new list. Same output as the four-line version — just clearer and shorter.
Note: Output: [1, 4, 9, 16]
Tip: The pattern is always [ EXPRESSION for ITEM in SEQUENCE ]. Read it as “collect EXPRESSION for each ITEM.”
Add a filter with if
You can keep only some items by adding an if at the end — it acts as a filter, letting through only the values that pass the test.
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)The new part is if n % 2 == 0 on the end. Remember % gives the remainder and an even number divided by 2 leaves remainder 0, so this keeps only the even numbers. Python checks each n, lets the evens through, and collects them — giving [2, 4, 6]. Odd numbers are silently skipped.
Note: Output: [2, 4, 6]
A realistic example
Comprehensions shine on real data. Say you have a list of prices and want a new list with 10% tax added, but only for items over 100:
prices = [50, 120, 200, 80]
taxed = [round(p * 1.1, 2) for p in prices if p > 100]
print(taxed)Here if p > 100 keeps only 120 and 200. For each of those, p * 1.1 adds 10% and round(..., 2) rounds to two decimal places. The result is a clean new list of taxed prices for the expensive items only — a transform and a filter together in one readable line.
Note: Output: [132.0, 220.0]
Set and dict comprehensions
The same idea works with curly braces to build a set (unique values) or a dictionary (key–value pairs). For a dict you supply both a key and a value with a colon.
words = ["apple", "mango", "apple"]
lengths = {w: len(w) for w in words}
print(lengths)
unique_lengths = {len(w) for w in words}
print(unique_lengths)The first comprehension uses w: len(w) — for each word it stores the word as the key and its length as the value, building a dictionary. Because dictionaries cannot have duplicate keys, the repeated apple simply appears once. The second uses curly braces with a single value, len(w), so it builds a set of the distinct lengths.
Note: Output: {'apple': 5, 'mango': 5} {5}
Q. What does [n * 2 for n in [1, 2, 3]] produce?
✍️ Practice
- Use a list comprehension to make a list of the cubes (n ** 3) of 1 to 5.
- Use a comprehension with an if to keep only words longer than 4 letters from a list.
🏠 Homework
- Given a list of temperatures in Celsius, build a new list of those values converted to Fahrenheit (c * 9/5 + 32) using one comprehension.