…
…
Python Programming Fundamentals · Lesson 30 / 40 · Comprehensions
PreviewIn this lesson you will
for, if, and append pattern into a list comprehension, and turn a comprehension that is hard to read back into a loopYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada is going to raise every price at Corner Café by $0.50, and under the menu she will show the items under $2.00 in an "affordable" corner. You can already do both with a loop: an empty list, for, an if when needed, then append. In this lesson you will learn to write the same job in one line, and when you should not turn a loop into one line.
The program you will write by the end of this lesson takes the five prices on the menu (latte 4.25, cookie 2.00, tea 1.25, brownie bite 1.75, water 0.75) and produces these two lines:
Output[4.75, 2.5, 1.75, 2.25, 1.25]
[1.25, 1.75, 0.75]The first line is the prices with the $0.50 increase, and the second line is the prices of the items under $2.00. You can build these two lists the way you have known since lesson 24. But the "open an empty list, walk through, add" pattern is written so often that Python offers a short syntax for it: the list comprehension. The name stays in English, and you can think of it as a "list builder".
In this lesson you will:
Why do you need it? So far you have always written three lines to transform a list: an empty list, a for line, and an append inside. The real information in these three lines sits in two places: what you walk through (for p in prices) and what you make from each element (p + 0.50). The rest, opening the empty list and writing append every time, is the pattern that is the same in every loop. A comprehension removes that pattern and leaves only the two pieces of real information.
Let's start with the way you know, and then do the same job in one line.
Example 1 (case): A $0.50 increase on every price
prices = [4.25, 2.00, 1.25, 1.75, 0.75]
# 1. The way you know: empty list, for, append
raised = []
p prices:
raised.(p + 0.50)
(raised)
raised = [p + 0.50 p prices]
(raised)
(prices)Comprehensions are not specific to the café. A teacher wants to separate the passes (50 and above) from the exam grades and give everyone a 5-point curve; a grade that goes over 100 with the curve should stay at 100.
grades = [72, 45, 88, 50, 39] # 1. Filtering: 50 and above passes = [g for g in grades if g >= 50] # 2. Transforming: add 5 points, do not go over 100 curved = [min(g + 5, 100) for g in grades] print(passes, len(passes)) print(curved)
Output[72, 88, 50] 3
[77, 50, 93, 55, 44]To find the number of students who passed, you did not keep a separate counter: the length of the filtered list (len) is enough. min(g + 5, 100) gives the smaller of two numbers; this way someone with 98 gets 100, not 103. Now it is your turn: find the grades that are still 50 and above after the curve with a single comprehension (expected [77, 50, 93, 55]). Then write the same job with a loop and compare the two outputs.
Try it now· not graded; doesn't affect progress
Using the variable of a comprehension afterward. The p in a comprehension looks like the for p in ... of a loop; but unlike the variable of a loop, it lives only inside the square brackets. Like the local names of the function in lesson 16, when the bracket closes, p is gone too.
def raise_prices(prices): raised = [p + 0.50 for p in prices] print(raised) print(p) raise_prices([4.25, 2.00, 1.25])
Error:
Output[4.75, 2.5, 1.75]
Traceback (most recent call last):
...
print(p)
^
NameError: name 'p' is not definedThe comprehension line ran and the list was printed; the error comes on the next line, because the name p was never defined outside. If you need the last element, read it from the result list: print(raised[-1]) → 1.75.
[expression for x in items] makes a value from each element and builds a new list; it does not touch the list it walks through, and its result must be assigned to a variable.[p for p in prices if p < 2.00]; Python looks at the condition first, then applies the expression at the front to the elements that pass it.for, at most one if, append", turn it into a comprehension; code that builds up a total, prints, or makes you stop as you read stays a loop.Next lesson: sorted and max have so far compared elements with themselves; to sort records by amount, you will give them a function.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output[4.75, 2.5, 1.75, 2.25, 1.25]
[4.75, 2.5, 1.75, 2.25, 1.25]
[4.25, 2.0, 1.25, 1.75, 0.75]Read the one-liner like a sentence: "for each p in prices, p + 0.50". The square brackets say the result will be a list. Inside the brackets, you first write the value to make from each element (p + 0.50), then the for line you already know (for p in prices); there is no colon at the end and no indentation. Whatever is inside append(...) in the loop moves to the front of the comprehension. Also look at the last print line: prices stays exactly as it was. A comprehension always builds a brand-new list; it does not touch the list it walks through. The cookie's 2.00 also came out as 2.5 because Python drops a trailing zero when it prints a float, and the list keeps floats as floats.
The table below shows the same three jobs in both ways side by side. In each row, notice that the expression inside append moves to the front of the comprehension, while the for part stays the same.
| With a loop | With a comprehension |
|---|---|
new = [] · for p in prices: · new.append(p + 0.50) | new = [p + 0.50 for p in prices] |
new = [] · for i in items: · new.append(i.upper()) | new = [i.upper() for i in items] |
new = [] · for n in range(1, 4): · new.append(n * n) | new = [n * n for n in range(1, 4)] |
The expression at the front does not have to be arithmetic: it can call a method, use a function, or read a field from a dictionary. Text that comes from an order screen is often messy: capital letters, extra spaces. Cleaning each piece with split, strip, and lower from lesson 21 and putting the pieces in a new list fits this pattern exactly.
Example 2 (case): Cleaning messy order text
text = " Latte, TEA ,Water " clean = [i.strip().lower() for i in text.split(",")] print(clean)
Output['latte', 'tea', 'water']text.split(",") first gives the list [' Latte', ' TEA ', 'Water ']. The comprehension takes each piece of this list, first removes the spaces at the edges, then changes it to lowercase. Follow the code below step by step. Notice that the raised box does not fill element by element as in a loop but all at once when the line ends, and that the prices box never changes.
Run the code line by line: see which line runs next, the variable boxes and the output.
prices = [1.25, 4.25, 2.00] raised = [p + 0.25 for p in prices] pricey = [p for p in prices if p > 1.50] print(raised) print(pricey)
Now it is your turn to translate between the two ways. For each loop on the left, pick the comprehension that does the same job. One option is extra; read carefully.
Pick the comprehension for each loop.
For each row, pick its match from the list, then check.
for p in prices: new.append(p * 2)for i in items: new.append(i.upper())for p in prices: if p < 2.00: new.append(p)for o in orders: new.append(o["item"])for n in range(1, 4): new.append(n * n)The most common misunderstanding is thinking that a comprehension changes the original list. Predict without running it:
What does this code print?
prices = [4.25, 2.00] new = [p * 2 for p in prices] print(prices)
Why do you need it? Ada's second request is not to make a value from every element but to leave out some elements completely: keep only the ones under $2.00. In lesson 12 you did this by putting an if inside the loop; append ran only when the condition was true. In a comprehension, this if is written at the very end: [p for p in prices if p < 2.00]. Read it as: "for each p in prices, if p < 2.00, p". The expression at the front is just p here, so the element is taken as it is.
Transforming and filtering can also be used together: [p + 0.50 for p in prices if p < 2.00] filters first, then transforms what is left, and gives [1.75, 2.25, 1.25]. For each element, Python looks at the condition at the end first; if the condition is false, the expression at the front is never calculated for that element.
Since unit 4 you have been putting a job into a function and calling it with different inputs. A comprehension fits very well as a single return line in the body of a function. The target program of this lesson looks like this:
Example 3 (case): The target program of the lesson
def affordable_prices(prices, limit): # Return the prices under the limit in a new list return [p for p in prices if p < limit] prices = [4.25, 2.00, 1.25, 1.75, 0.75] print([p + 0.50 for p in prices]) print(affordable_prices(prices, 2.00))
Output[4.75, 2.5, 1.75, 2.25, 1.25]
[1.25, 1.75, 0.75]The cookie costs exactly $2.00 and is not in the list, because < does not accept equality. If "$2.00 and under" were wanted, you would write <=. Predict what the code below prints; think about whether the condition at the end or the expression at the front runs first.
What does this code print?
print([n * 2 for n in range(4) if n % 2 == 1])
Press the buttons below to see how the list changes as the limit changes. Look at two cases in particular: when the limit is 2.00, does 2.00 itself get into the list, and what happens when the limit is 0.75?
Change the limit: which prices go into the "affordable" corner?
Pick a value; predict the output first, then look.
1prices = [4.25, 2.00, 1.25, 1.75, 0.75]2limit = 2.003affordable = [p for p in prices if p < limit]4print(affordable)5print(len(affordable), "items")
[1.25, 1.75, 0.75] 3 items
Faded lines didn't run with this value. When the limit is 0.75, no price is less than 0.75 (the water is exactly 0.75) and the result is an empty list; it does not cause an error. When the limit is 2.00, the cookie (2.00) stays out, because < does not accept equality. When the limit is 5.00, every price passes the filter.
The filter works not only on lists of numbers but also on lists of records and tuples. You can read fields from the order records of lesson 28, and you can unpack the tuples of lesson 29 in the for line.
Example 4 (case): Comprehensions on a list of records and a list of tuples
orders = [
{"item": "latte", "qty": 2, "price": 4.25},
{"item": "tea", "qty": 3, "price": 1.25},
{"item": "water", "qty": 2, "price": 0.75},
]
amounts = [o["qty"] * o["price"] for o in orders]
print(amounts, sum(amounts))
menu = [("latte", 4.25), ("tea", 1.25), ("water", 0.75), ("cookie", 2.00)]
print([name for name, price in menu if price < 2.50])Output[8.5, 3.75, 1.5] 13.75
['tea', 'water', 'cookie']The first comprehension calculates the amount of each record; the total is found not by a comprehension but by sum, which already exists. In the second, for name, price in menu unpacks each tuple into two names; the condition looks at price, and the expression at the front takes only name.
Why do you need it? Once you learn the comprehension, it is tempting to squeeze every loop into one line. But a comprehension is designed for one job only: making a new list from a list. If a loop does something other than that, for example printing to the screen or updating a total at every step, turning it into a comprehension breaks the code or makes it unreadable. To decide, look at the pattern of the loop:
| What does the loop do? | Choice | Why |
|---|---|---|
| Makes a value from each element and adds it to a new list | Comprehension | Exactly the pattern |
| Filters with a condition and adds to a new list | Comprehension | The condition goes at the end |
| Builds up a total or a counter | Loop (or sum, len) | Each step reads the previous value; it does not make a list |
| Prints to the screen | Plain for | print does not make a value; it returns None |
| Updates several variables together | Loop | A comprehension makes only one list |
Two for lines, conditions, a long expression: you stop and think as you read | Loop | What is readable is good, not what is short |
The practical rule is this: write it as a loop first. If your loop fits the pattern "empty list, one for, at most one if, append", turn it into a comprehension; if it does not fit, leave it as a loop. Let's see what happens when you try to do the printing job with a comprehension. Predict without running it:
What appears on the screen when these two lines run?
result = [print(i) for i in ["tea", "water"]] print(result)
An example that shows shorter is not always better: Ada keeps the bills of the tables in a nested list, and she wants to see the items more expensive than $1.00 in one list. This job can be written in one line, but you have to stop and think to read the line. You saw nested loops in lesson 13; the goal here is not to learn them again but to see how to turn a comprehension that is hard to read back into a loop.
Example 5 (case): Turning the unreadable one back into a loop
tables = [[4.25, 2.00], [1.25], [1.75, 0.75, 1.25]] # 1. One line: correct but hard to read print([p for table in tables for p in table if p > 1.00]) # 2. The same job with a loop: each line says one thing result = [] for table in tables: for p in table: if p > 1.00: result.append(p) print(result)
Output[4.25, 2.0, 1.25, 1.75, 1.25]
[4.25, 2.0, 1.25, 1.75, 1.25]The two ways make the same list. The two for parts in the one-liner are read from left to right, in the order of the outer and inner for in the loop; but you have to read the line several times to work that out. In the loop version, each line says one thing. Now build the loop version yourself, with its indentation.
Put the loop version of the comprehension in Example 5 in the right order, with its indentation.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
When the same syntax is used with curly braces instead of square brackets, it makes a set or a dictionary instead of a list. What is inside the braces tells which one is made: if there is a key: value pair inside, it is a dictionary; if there is a single expression, it is a set.
| Syntax | Structure made |
|---|---|
[x for x in items] | List |
{x for x in items} | Set (repeats are dropped, no order) |
{k: v for k, v in mapping.items()} | Dictionary |
{} | Empty dictionary (an empty set is made with set()) |
Example 6 (case): A menu dictionary with increased prices and item names without repeats
menu = {"latte": 4.25, "tea": 1.25, "water": 0.75}
print({i: p + 0.25 for i, p in menu.items()})
print(sorted({s.lower() for s in ["Latte", "tea", "LATTE", "Tea"]}))Output{'latte': 4.5, 'tea': 1.5, 'water': 1.0}
['latte', 'tea']The first line adds $0.25 to the price of each item and builds a new dictionary; menu again does not change. In the second line, the set keeps a single copy of the names that are the same after being changed to lowercase; sorted turns the result into a sorted list. One warning: the job in lesson 27 of "building up by reading the previous total at every step" (for example, counting quantity per item) is not done with a comprehension; the loop pattern there stays. Try it by changing the code in the cell below.
Try it now· not graded; doesn't affect progress