Skip to content

Intermediate · Working with data · topic 27 of 50 · 20 min

List, dict and set comprehensions

Explanation

A comprehension builds a new list, dict or set in one line from another collection, like [p * 2 for p in prices]. Add an if at the end to keep only some items. Comprehensions are short and fast, but when the logic grows long, a plain for loop is easier to read.

From a loop to one line

python
prices = [40, 120, 15, 300]

# with a loop
doubled = []
for p in prices:
    doubled.append(p * 2)
print(doubled)

# with a list comprehension
print([p * 2 for p in prices])
Both give [80, 240, 30, 600].

Read a list comprehension from the middle: "for p in prices" is the loop, and the part before it (p * 2) is what goes into the new list. The square brackets say "make a list".

Think of it like this: A comprehension is like ordering at a juice stall: "one glass of juice for every orange, but only the ripe ones." You state the rule once, and the stall does the whole loop for you.

Keeping only some items: if at the end

python
marks = [78, 32, 91, 45, 20]
passed = [m for m in marks if m >= 35]
print(passed)
Shows [78, 91, 45]. The if filters items out.

Changing each item: if-else at the front

python
marks = [78, 32, 91, 45, 20]
labels = ["pass" if m >= 35 else "fail" for m in marks]
print(labels)
Every item stays, but each becomes "pass" or "fail".
Careful: The two forms put the if in different places. A filter goes AFTER the for: [m for m in marks if m >= 35]. A choice between two values goes BEFORE the for, and needs an else: ["pass" if m >= 35 else "fail" for m in marks]. Writing [m if m >= 35 for m in marks] is a SyntaxError.

Dict and set comprehensions

python
names = ["Asha", "Ravi", "Meenakshi"]
print({name: len(name) for name in names})

prices = {"pen": 10, "bag": 500}
with_gst = {item: round(p * 1.18, 2) for item, p in prices.items()}
print(with_gst)

cities = ["Pune", "pune", "Delhi", "PUNE"]
print({c.lower() for c in cities})
Curly brackets with key: value make a dict; curly brackets with one value make a set.

Nested comprehensions (briefly)

python
grid = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in grid for x in row]
print(flat)
table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
print(table)
The for parts are read left to right, in the same order as nested loops.

Generator expressions: a preview

python
cart = [(40, 2), (120, 1), (15, 4)]   # (price, quantity)
print(sum(p * q for p, q in cart))
No square brackets: sum takes the values one by one, without building a list. Shows 260.
Tip: Use a comprehension when it fits on one readable line. If you need two ifs, a try/except, a print, or more than one step per item, write a normal for loop. Clear code beats clever code.

Watch the lesson

List, dict and set comprehensions · 1/7

Comprehensions

Comprehensions let you build a new list, dict or set in a single line. In this lesson you will learn all three.

Prefer a video by a teacher? Find free videos on “python list comprehension dict comprehension tutorial” on YouTube ↗

In real life: A festival sale price list

Lakshmi runs a saree shop. For the festival sale she gives 10% off on items above 500 rupees, and wants a new price list without touching the original. One dict comprehension builds the sale list, and a list comprehension picks the items that got a discount.

python
prices = {"cotton saree": 450, "silk saree": 3200, "dupatta": 350, "lehenga": 5400}
sale = {item: (p * 90 // 100 if p > 500 else p) for item, p in prices.items()}
print(sale)
print([item for item in prices if prices[item] > 500])
Silk saree and lehenga get 10% off; the others keep their price.

Practice (0/3 done)

Task 1 · Code · Python

Write squares_of_evens(nums) that returns a list of the squares of only the even numbers, in the same order. squares_of_evens([1, 2, 3, 4]) returns [4, 16]. Use one list comprehension.

Task 2 · Code · Python

Write grade_labels(marks) that returns a list with "pass" for every mark of 35 or more and "fail" for the rest, in the same order.

Task 3 · Code · Python

Write add_gst(prices, rate) where prices is a dict like {"pen": 10}. Return a new dict with the same keys and each price increased by rate percent, rounded to 2 places. add_gst({"pen": 10, "bag": 500}, 18) returns {"pen": 11.8, "bag": 590.0}.

Quick quiz

Question 1

1.What is [x * 2 for x in [1, 2, 3]]?

Question 2

2.What is [x for x in range(10) if x % 3 == 0]?

Question 3

3.Which line is valid Python?

Question 4

4.How many items are in {c for c in "banana"}?

Question 5

5.What does sum(x for x in range(5)) give?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: JSON and regular expressions