# Convert temperatures
= [22, 18, 25] # Example temperatures in Celsius
celsius = [(c * 9/5) + 32 for c in celsius]
fahrenheit print(fahrenheit)
[71.6, 64.4, 77.0]
List comprehensions in Python provide a concise way to create lists. They are used for transforming one list into another, where each element of the new list is the result of some operation applied to each member of the original list. List comprehensions are more compact and faster than using a for-loop to create lists.
To make an analogy, list comprehensions are to for loops, what lambda functions are to regular functions. Like lambda functions, list comprehensions offer a shorthand to define a new list. Both list comprehensions and lambda functions are about brevity and simplicity, that otherwise would require more verbose coding with for loops and regular functions.
If you have a list of daily average temperatures in Celsius from various farm locations, you can convert them to Fahrenheit using a list comprehension
# Convert temperatures
= [22, 18, 25] # Example temperatures in Celsius
celsius = [(c * 9/5) + 32 for c in celsius]
fahrenheit print(fahrenheit)
[71.6, 64.4, 77.0]
Suppose you have a list of crop yields in bushels per acre for a farm. You can easily calculate the yields in kilograms per hectare if you know the conversion factors between units.
= [120, 150, 180] # Example yields in bushels
bushels_per_acre = 25.4 # Conversion factor for corn
kg_per_bushel = 0.405
acres_per_hectare
= [round(yld * kg_per_bushel / acres_per_hectare) for yld in bushels_per_acre]
kg_per_hectare print(kg_per_hectare)
[7526, 9407, 11289]
This example is a bit more advanced and also includes if
statements.
# Classify soil pH into acidic, neutral, or alkaline.
= [6.5, 7.0, 8.2]
soil_ph = ['acidic' if ph < 7 else 'alkaline' if ph > 7 else 'neutral' for ph in soil_ph]
ph_class print(ph_class)
['acidic', 'neutral', 'alkaline']