Lesson 21 of 35Python
Python · Lesson 21 · 25 minutes
List comprehensions
What you'll learn
- Create lists in a single line
- Filter with
ifinside a comprehension - Write dictionary comprehensions
A list in one line
You already know this way of filling a list:
squares = []
for x in range(1, 6):
squares.append(x * x)
print(squares)A list comprehension does the same in one line:
squares = [x * x for x in range(1, 6)]
print(squares)Read it like this: “Take x times x for every x in range(1, 6).”
Filtering with if
You can add a condition at the end. Only items for which it is true end up in the new list:
grades = [1, 4, 2, 5, 3, 2, 6]
good = [g for g in grades if g <= 2]
print(good)
names = ["mia", "ben", "lea"]
print([n.upper() for n in names if n != "ben"])Dictionaries and sets
With curly brackets it works for dictionaries too:
prices = {"apple": 0.5, "bread": 2.0, "cheese": 3.5}
on_sale = {item: round(price * 0.9, 2) for item, price in prices.items()}
print(on_sale)
letters = {l for l in "programming"}
print(sorted(letters))Remember: Comprehensions are great for short transformations. If one gets so long you can hardly read it, a normal
forloop is better.
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
words = ["a", "bc", "def"]
print([w.upper() for w in words if len(w) > 1])Your task
Your turn
Create with one comprehension each: the list squares with the square numbers from 1 to 10, the list even with all even numbers from numbers, and the dictionary lengths that maps every word in words to its length.
numbers = [3, 8, 15, 22, 7, 40]
words = ["Robo", "Python", "Code"]
squares = []
even = []
lengths = {}
print(squares)
print(even)
print(lengths)- Something to think about
[x
**2forx inrange(1, 11)] – range stops before 11. - Which command helps?
Filter with
ifn%2==0 at the end of the comprehension.Dictionary comprehension: {w:
len(w)forw in words} - Gap code – fill in the ___
numbers = [3, 8, 15, 22, 7, 40] words = ["Robo", "Python", "Code"] squares = ___ even = ___ lengths = ___ print(squares) print(even) print(lengths)
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
numbers = [3, 8, 15, 22, 7, 40]
words = ["Robo", "Python", "Code"]
squares = [x ** 2 for x in range(1, 11)]
even = [n for n in numbers if n % 2 == 0]
lengths = {w: len(w) for w in words}
print(squares)
print(even)
print(lengths)