Comprehensions
Python · Unit 5: Lists
- Full plan
- Python
- 12 exercises
A comprehension builds a list out of another one in a single line: [what you keep for x in list].
It does the same as a for with append.
nums = [10, 20, 30]
doubles = [n * 2 for n in nums]
print(doubles)Prints
[20, 40, 60]
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Multiple choice
Which comprehension does the same as this code?
3. Complete the code
Complete it to turn the pounds into ounces.
4. Predict the output
What does this code print?
5. Complete the code
Complete it to keep the failing scores (under 60).
6. Predict the output
What does this code print?
7. Find the bug
This program should print the line in alphabetical order. Which line has the error?
8. Multiple choice
You want to see your expenses sorted, but without losing the order you wrote them down in. What do you use?
9. Predict the output
What does this code print?
10. Complete the code
Complete it to sort the points from highest to lowest.
11. Write the code
Write
doubles(nums), which returns a new list with each number multiplied by 2. Use a comprehension.12. Predict the output
These are the points of four players. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.