Filtering Comprehensions
Add an if at the end of a comprehension to keep only the values that match a condition.
temperatures = [18, 27, 31, 22, 35]
warm = [temp for temp in temperatures
if temp >= 25]
fahrenheit = [temp * 9 / 5 + 32
for temp in temperatures
if temp < 25]
print(warm)
print(fahrenheit)
Output:
[27, 31, 35]
[64.4, 71.6]
Python checks the condition first. Only the values that pass it go to the expression at the start, which changes them. In fahrenheit, only 18 and 22 are below 25, so only they are turned into Fahrenheit.
Keep comprehensions short. When you need many conditions and changes, a regular loop is easier to read.
In the exercise, filter a list in two ways, then filter it and square the numbers.