Comprehensions: New Lists in One Line
A comprehension builds a new list, dictionary or set from another collection in one line, written as what goes in, for each item, if a condition holds, and replaces the empty-list-and-append loop whenever the whole job is building one collection.
Apprentice · Python · Updated
After this lesson you can
- Build a new list from another collection with a list comprehension, with or without an if condition
- Build a dictionary or a set with a comprehension, and choose a plain loop when it reads better
Key takeaways
- A list comprehension such as [amount * 2 for amount in cups] is read "amount times 2, for each amount in cups". It builds a new list and leaves the old one as it was.
- An if at the end keeps only the items that pass, as in [name for name in names if len(name) < 8].
- Curly braces with a key, a colon and a value build a dictionary, and curly braces with one expression build a set.
- A plain for loop reads better when the job has several steps, prints as it goes, or changes something.
Much of programming is making one collection out of another: every price with the tax added, only the students who passed, each name in capital letters. The loop that does it is the same few lines every time, and Python has a shorter way to write it that you'll see in nearly every Python program you read: the comprehension.
Pantry Pal, a recipe app, is scaling recipes up for a party and picking what to cook tonight.
The same loop, again and again
The pancake recipe takes 2 cups of flour, 1 cup of milk and half a cup of sugar. For a party, every amount doubles:
cups = [2, 1, 0.5]
doubled = []
for amount in cups:
doubled.append(amount * 2)
print(doubled)
[4, 2, 1.0]
Make an empty list, loop, append, and the new list is ready. Of those lines, only amount * 2 is about this job. The rest is scaffolding you write the same way every time: for prices with tax, for names in capitals, for anything.
A list comprehension
A list comprehension writes the same loop in one line:
cups = [2, 1, 0.5]
doubled = [amount * 2 for amount in cups]
print(doubled)
print(cups)
[4, 2, 1.0]
[2, 1, 0.5]
The square brackets say "a new list". Inside, read it aloud: "amount times 2, for each amount in cups". What goes into the new list comes first, then the same for as the loop's. The old list is left as it was.
Add an if at the end, and only the items that pass go in. Here, the recipes you can cook in half an hour:
times = {"Pancakes": 20, "Omelet": 10, "Banana bread": 65, "Chili": 45}
quick = [name for name, minutes in times.items() if minutes <= 30]
print(quick)
['Pancakes', 'Omelet']
Read it as "name, for each name and minutes in the times' items, if minutes is 30 or less". The whole pattern is [what goes in for item in collection if condition], and the if part is optional.
Dictionary and set comprehensions
Curly braces make the other two kinds. With a key, a colon and a value, it's a dictionary comprehension; with one expression, it's a set comprehension:
pancakes = {"eggs": 2, "flour": 2, "milk": 1}
party = {ingredient: amount * 3 for ingredient, amount in pancakes.items()}
print(party)
typed = ["Eggs", "eggs", "Flour", "MILK", "milk"]
clean = {item.lower() for item in typed}
print(sorted(clean))
{'eggs': 6, 'flour': 6, 'milk': 3}
['eggs', 'flour', 'milk']
The first tripled every amount and kept each ingredient as its key. The second tidied a list people typed: each item in lowercase, and since it's a set, each one once.
When a plain loop reads better
A comprehension does one job: building a collection. When the work has several steps, prints as it goes, or changes something, a loop says it more clearly:
pantry = {"eggs": 6, "flour": 1, "milk": 0}
for ingredient, amount in pantry.items():
if amount == 0:
print(f"Out of {ingredient}: add it to the shopping list")
elif amount < 2:
print(f"Low on {ingredient}: {amount} left")
Low on flour: 1 left
Out of milk: add it to the shopping list
Squeezing two conditions and two messages into one comprehension would make it shorter and much harder to read. A good rule: if you can read a comprehension aloud in one breath, write it; if you can't, write the loop.
Do it: list what's running low
Pantry Pal warns you about ingredients that are running low before you start cooking.
pantry: a dictionary of each ingredient's name to the amount you have.limit: an amount is low when it's below this number.
Your job: write the function low_stock(pantry, limit) so it returns a list of the names of the ingredients whose amount is below limit.
- An amount equal to
limitisn't low. - The names come in the same order as in the pantry.
- When nothing is low, it returns an empty list,
[].
Worked through: with pantry = {"eggs": 6, "flour": 1, "milk": 0, "sugar": 3} and a limit of 3, flour (1) and milk (0) are below 3, eggs (6) aren't, and sugar (3) is equal to 3, so it isn't low. low_stock(pantry, 3) returns ["flour", "milk"].
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
A comprehension says what a new collection holds in one line you can read aloud, which is why Python programmers use one for nearly every list, dictionary and set they build from another.