Filtering and Transforming
Map Transform
Apply a formula to every element of a list, collecting the results in a new
list. Here, Celsius readings are converted to Fahrenheit. The replay shows
the intermediate result f computed on each iteration before it is appended.
By hand
The Pythonic way
A list comprehension [c * 9 / 5 + 32 for c in celsius] applies the formula
to every element in one expression, with no accumulator or append call.
naive.py
celsius = [0, 20, 37, 100, -10, 25]
fahrenheit = []
for c in celsius:
f = c * 9 / 5 + 32
fahrenheit.append(f)
print('RESULT:', fahrenheit)
library.py
celsius = [0, 20, 37, 100, -10, 25]
fahrenheit = [c * 9 / 5 + 32 for c in celsius]
print('RESULT:', fahrenheit)
RESULT: [32.0, 68.0, 98.6, 212.0, 14.0, 77.0]
Implementation notes
- The chosen values all produce clean decimal results; no rounding is needed at the print boundary.
list(map(lambda c: c * 9 / 5 + 32, celsius))is an equivalent functional form; the list comprehension is preferred in modern Python for readability.- The comprehension runs in its own scope, so neither
cnor the intermediate result appears as a traced variable in the library half.