Statement
Solution
Python Exercise 10.1: List Comprehensions
List comprehensions are one of Python's most powerful and expressive features. They let you build a new list from an existing one in a single, readable line — replacing multi-line for loops.
Your program should:
- Start with a list of Celsius temperatures:
[0, 20, 37, 100, -10, 25]. - Use a list comprehension to convert every value to Fahrenheit using the formula:
F = (C × 9/5) + 32. - Print the original Celsius list.
- Print the converted Fahrenheit list, rounded to 1 decimal place.
- Bonus: Use a second list comprehension with an
iffilter to print only the Fahrenheit values that are above freezing (i.e. > 32).
Sample Interaction:
Input
Output
(None)
Celsius: [0, 20, 37, 100, -10, 25]
Fahrenheit: [32.0, 68.0, 98.6, 212.0, 14.0, 77.0]
Above freezing: [68.0, 98.6, 212.0, 77.0]
Solution
One comprehension converts all values; a second chained comprehension filters the result — both in a single line each.
# 1. Original Celsius list
celsius = [0, 20, 37, 100, -10, 25]
# 2. Convert to Fahrenheit using a list comprehension
fahrenheit = [round((c * 9/5) + 32, 1) for c in celsius]
# 3. Filter: only values above freezing (> 32)
above_freezing = [f for f in fahrenheit if f > 32]
# 4. Print results
print(f"Celsius: {celsius}")
print(f"Fahrenheit: {fahrenheit}")
print(f"Above freezing: {above_freezing}")
Key Concepts:
- Basic syntax:
[expression for item in iterable] - With filter:
[expression for item in iterable if condition] - List comprehensions are faster than equivalent
forloops and more Pythonic. round(value, 1)rounds a float to 1 decimal place — works seamlessly inside the expression.- You can chain comprehensions: filter the output of one inside another.
Test Console
Run code to see output...