Transform Values with a Comprehension
Derive one list comprehension from its complete loop, then read a filter, a conditional result, and one small nested form by expanding them.
A loop can build a new list while keeping every step visible. After that loop is understood, a list comprehension can express the same simple rule in one place.
Begin with the Complete Loop
Suppose a sensor needs a correction of 0.5 degrees:
The result is [18.5, 21.5, 20.5, 23.5]. The source list is unchanged; the
loop builds a separate result list.
The equivalent list comprehension is:
corrected = [reading + 0.5 for reading in readings]
Read it from the for clause:
- take each
readingfromreadings; - calculate
reading + 0.5; - place that result in the new list.
Q1. Read a simple comprehension
What list does this expression build?
[reading - 1 for reading in [18, 21, 20]]
Compute it first, then check your number.
HintKeep the order
Transform 18, then 21, then 20.
SolutionTransform every item
The results are 17, 20, and 19, so the new list is [17, 20, 19].
Add One Filter When Some Items Should Be Omitted
Chapter 3 used None for an unavailable reading. The loop form filters those
values before transforming the others:
The matching comprehension places the filter after the for clause:
Read the filter first: only an available reading continues to the result
expression. A filter may make the output shorter than the input.
This is different from a conditional expression, which produces one result for every input:
labels = ["high" if reading >= 22 else "ordinary" for reading in [18, 22, 20]]
The three inputs produce three labels. The conditional expression chooses which label to add; it does not omit an item.
Q2. Filter before transforming
What list is produced?
[reading * 2 for reading in [3, None, 5] if reading is not None]
Compute it first, then check your number.
HintDecide which inputs continue
Only 3 and 5 reach reading * 2.
SolutionTwo values continue
The filter removes None, then the expression produces 6 and 10.
Expand a Nested Form Before Trusting It
A small nested comprehension can flatten two short runs of readings:
Expand it into the loops that execute in the same order:
Both forms build [18, 20, 21, 23]. The explicit loop is usually clearer when
there are several filters, several calculations, or intermediate values worth
naming. Compactness is not a reason to hide a procedure.
Q3. Build the filtered result
Complete the comprehension so the program displays [18.5, 20.5].
Editable Python
Ready to run.
HintFollow the loop order
Write reading + 0.5 for reading in readings if reading is not None.
SolutionFilter and transform
A list comprehension can replace one clear result-building loop, and the loop remains the reliable way to explain it. The next lesson keeps the same transformation visible when a summary needs the values but the program does not need the intermediate list.