23  List comprehensions

Author

Andres Patrignani

Published

January 25, 2024

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.

Example 1: Convert temperature units

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
celsius = [22, 18, 25]  # Example temperatures in Celsius
fahrenheit = [(c * 9/5) + 32 for c in celsius]
print(fahrenheit)
[71.6, 64.4, 77.0]

Example 2: Conver from lbs/acre to kg/ha

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.

bushels_per_acre = [120, 150, 180]  # Example yields in bushels
kg_per_bushel = 25.4  # Conversion factor for corn
acres_per_hectare = 0.405

kg_per_hectare = [round(yld * kg_per_bushel / acres_per_hectare) for yld in bushels_per_acre]
print(kg_per_hectare)
[7526, 9407, 11289]

Example 3: Classify soil pH

This example is a bit more advanced and also includes if statements.

# Classify soil pH into acidic, neutral, or alkaline.
soil_ph = [6.5, 7.0, 8.2] 
ph_class = ['acidic' if ph < 7 else 'alkaline' if ph > 7 else 'neutral' for ph in soil_ph]
print(ph_class)
['acidic', 'neutral', 'alkaline']