Programming with Python · free preview
Comprehensions
Build new lists, dictionaries, and sets from existing data with one readable expression instead of a loop.
1. Overview
Overview
2. Building Lists from Lists
Building Lists from Lists
3. Filtering with Conditions
Filtering with Conditions
4. Dictionary and Set Comprehensions
Dictionary and Set Comprehensions
5. Keeping It Readable
Keeping It Readable
6. Square the Odds
Square the Odds
7. Length Filter
Length Filter
8. Choose the filter position
Which comprehension keeps only positive values from readings?
9. Trace comprehension mapping, filtering, and dictionaries
Work through the full example, including exact outputs and reasoning.
Example. Trace comprehension mapping, filtering, and dictionaries
Problem. Work through the full example, including exact outputs and reasoning.
Correct solution.
Input,celsius = [36.6, 38.4, 37.0, 39.1].
Step 1, map with a list comprehension.
fahrenheit = [round(value * 9 / 5 + 32, 2) for value in celsius]
print(fahrenheit)Output.```output [97.88, 101.12, 98.6, 102.38]
Reasoning, the output expression runs once per source item, in source order.
Step 2, filter to fever readings.
```python
hot = [value for value in celsius if value >= 38.0]
print(hot)Output.```output [38.4, 39.1]
Reasoning, the `if` clause decides membership before any output expression is stored.
Step 3, combine filtering and transformation.
```python
report = {round(value * 9 / 5 + 32, 2): value for value in celsius if value >= 38.0}
print(report)Output.``output {101.12: 38.4, 102.38: 39.1} ``
Reasoning, the key expression comes first, then the source, then the filter. Repeated keys would be overwritten by later items.
关键提醒。
A comprehension reads as output, source, and optional filter; filters remove items while transformations change them.
10. Retrieval practice
Use this new input without looking back, readings = [40.1, 36.8, 39.4, 36.7]. Write the list comprehension that keeps readings of at least 39.0 and divides them by 2, and state the exact output.
Give the one-line expression and the exact printed result.
11. Mastery check
Apply comprehensions to visits = [('Alice', 36.8), ('Bob', 39.2), ('Carol', 39.0), ('Dan', 36.6)]. Without a loop, build a dictionary mapping each name to fever when the second value is at least 39.0 and to normal otherwise. Give the expression and exact output.
Show the dictionary comprehension and exact output.
Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free