Python Comprehensions
The numbers are already written: 2, then 5, then 1. One line builds another list from them. doubled = [n * 2 for n in prices] walks each number, doubles it, and stores 4, then 10, then 2. prices is not rewritten. n is only the name of the number the line is on: first 2, then 5, then 1.
prices = [2, 5, 1]
doubled = [n * 2 for n in prices]
print(doubled[0])
print(doubled[1])
print(len(prices))
The screen shows 4, then 10, then 3. 4 is the first new number, 2 doubled. 10 is the next, 5 doubled. The 3 is how many numbers prices still has. The last new number is 2, from 1 doubled, and this program does not print it.
prices[0] is still 2. Doubling wrote a new list. It did not replace the old one. When the line is finished, you read doubled. n was only in use while the line was walking.
A test can leave a number out. This program starts on its own, so doubled is not here. small = [n for n in prices if n < 5] keeps a number only when it is under 5. 2 goes in. 5 does not. 1 goes in. The new list is 2, then 1. prices still has three numbers.
prices = [2, 5, 1]
small = [n for n in prices if n < 5]
print(small[0])
print(len(small))
The screen shows 2, then 2. The first 2 is small[0], the number 2 that was kept. The second 2 is how many numbers were kept. 5 is not in small. small[1] would be 1, and this program does not print it.
📊 Double, keep, or stop
| Line | What you get |
|---|---|
| [n * 2 for n in prices] | a new list 4, 10, 2, and prices stays |
| [n for n in prices if n < 5] | a new list 2, then 1, and 5 stays out |
| prices[0] | still 2 |
| n * 2 for n in prices | the program stops, because the brackets are missing |
The brackets belong to the line. Without them the program stops. The name in front and the name after for have to be the same name. [n * 2 for price in prices] stops too, because n never receives a number. price would be the name that walks, and the doubled part never uses it.
The next page is about the name of a stop, when the program hits a problem. This page only builds a list in one line.
What the two lists show
- What does the first program write?
- After that program, what is prices[0]?
- What does the second program write?
- What happens if you write the doubling line without the brackets?
A new list, and the old one stays
The first screen is 4, then 10, then 3. prices[0] is still 2. The second screen is 2, then 2: the first kept number, then how many were kept. 5 stayed out. Leave the brackets off and the program stops. The name you double and the name after for are the same name. The next page is about the name of a stop.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top