Intermediate · Working with data · topic 27 of 50 · 20 min
List, dict and set comprehensions
Explanation
From a loop to one line
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])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".
Keeping only some items: if at the end
marks = [78, 32, 91, 45, 20]
passed = [m for m in marks if m >= 35]
print(passed)Changing each item: if-else at the front
marks = [78, 32, 91, 45, 20]
labels = ["pass" if m >= 35 else "fail" for m in marks]
print(labels)Dict and set comprehensions
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})Nested comprehensions (briefly)
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)Generator expressions: a preview
cart = [(40, 2), (120, 1), (15, 4)] # (price, quantity)
print(sum(p * q for p, q in cart))Watch the lesson
List, dict and set comprehensions · 1/7
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.
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])Practice (0/3 done)
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.
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.
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
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.