List comprehensions#

Programming for Geoscientists Data Science and Machine Learning for Geoscientists

List comprehensions are ‘shortcuts’ in creating lists using loops within one statement. The main advantage is that they are shorter to write. The syntax is:

    some_list = [expression for item in iterable_object if condition]

This will generate a list with an expression based on items in ‘iterable_object’, if the condition is met. The if condition is optional.

# List comprehensions

normal_numbers = [number for number in range(1, 20, 3)]
print(normal_numbers)

cubic_numbers = [number**3 for number in range(1, 20, 3)]
print(cubic_numbers)

# These are equivalent to 

normal_numbers = []
cubic_numbers = []

for number in range(1, 20, 3):
    normal_numbers.append(number)
    cubic_numbers.append(number**3)
    
print(normal_numbers)
print(cubic_numbers)
[1, 4, 7, 10, 13, 16, 19]
[1, 64, 343, 1000, 2197, 4096, 6859]
[1, 4, 7, 10, 13, 16, 19]
[1, 64, 343, 1000, 2197, 4096, 6859]

The expression in list comprehension can be anything, the same value for each item, a string…:

zeros_list = [ 0 for i in range(5)]
text_list = ["text" for i in range(5)]

print(zeros_list)
print(text_list)
[0, 0, 0, 0, 0]
['text', 'text', 'text', 'text', 'text']

Using if condition:

# List comprehension with if statement
# number%2 == 1 means to search for numbers whose 
# remainder from division by 2 is 1 (odd numbers)

odd_numbers = [ number for number in range(20) if number%2 == 1]
print(odd_numbers)

# Equivalent to

odd_numbers = []
for number in range(20):
    if number%2 == 1:
        odd_numbers.append(number)
        
print(odd_numbers)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Exercises:#


  • Create a list comprehension to find Celsius temperatures for Fahrenheit temperatures between \(20^\circ\)F and \(80^\circ\)F at \(5^\circ\)F increments. The Fahrenheit-Celsius conversion formula is:

\[ T_{Celsius} = \frac{5}{9}*(T_{Fahrenheit}-32). \]
  • Create a list of powers of two \(2^x\) where \(x\) is positive, odd, not divisible by 3 and smaller than 40. Iterate through that list and print the last integer of each element. Numbers tend to show up patterns in such analysis, can you spot one?