121. More list comprehension examples

Example 1 – double the numbers

Standard loop approach:

foo = [1, 2, 3, 4]
bar = []

for x in foo:
    bar.append(x * 2)
    
print(bar)

Out:

[2, 4, 6, 8]

Using list comprehension:

foo = [1, 2, 3, 4]
bar = [x * 2 for x in foo]
print(bar)

Out:

[2, 4, 6, 8]

Example 2 – convert Celsius to Fahrenheit

This example calls a function from within the list comprehension.

Define the function:

def convert_celsius_to_fahrenheit(deg_celsius):
    """
    Convert degress celsius to fahrenheit
    Returns float value - temp in fahrenheit
    Keyword arguments:
        def_celcius -- temp in degrees celsius
    """
    return (9/5) * deg_celsius + 32

Standard loop approach:

#list of temps in degree celsius to convert to fahrenheit
celsius = [39.2, 36.5, 37.3, 41.0]

#standard for loop approach
fahrenheit = []
for x in celsius:
    fahrenheit.append(convert_celsius_to_fahrenheit(x))

print('Using standard for loop: {}'.format(fahrenheit))

Out:

Using standard for loop: [102.56, 97.7, 99.14, 105.8]

Using list comprehension

fahrenheit = [convert_celsius_to_fahrenheit(x) for x in celsius]
print('Using list comprehension: {}'.format(fahrenheit))

Out:

Using list comprehension: [102.56, 97.7, 99.14, 105.8]

Example 3 – convert the strings to different data types

This example also make use of the zip function. Zip allows you to iterate through two lists at the same time.

inputs = ["1", "3.142", "True", "spam"]
converters = [int, float, bool, str]

values_with_correct_data_types = [t(s) for (s, t) in zip(inputs, converters)]
print(values_with_correct_data_types)

Out:

[1, 3.142, True, 'spam']

Example 4 – Using if statements within a list comprehension

The example filters a list of file names to the python files only

unfiltered_files = ['test.py', 'names.csv', 'fun_module.py', 'prog.config']

# Standard loop form
python_files = []
# filter the files using a standard for loop 
for file in unfiltered_files:
    if file[-2:] == 'py':
        python_files.append(file)
        
print('using standard for loop: {}'.format(python_files))

#list comprehension
python_files = [file for file in unfiltered_files if file[-2:] == 'py']

print('using list comprehension {}'.format(python_files))

Out:

using standard for loop: ['test.py', 'fun_module.py']
using list comprehension ['test.py', 'fun_module.py']

Example 5 – List comprehension to create a list of lists

list_of_lists = []

# Standard loop form
for i in range(5):
    sub_list = []
    for j in range(3):
        sub_list.append(i * j)
    list_of_lists.append(sub_list)

print(list_of_lists)


# List comprehension
list_of_lists = [[i * j for j in range(3)] for i in range(5)]

print(list_of_lists)

Out:

[[0, 0, 0], [0, 1, 2], [0, 2, 4], [0, 3, 6], [0, 4, 8]]
[[0, 0, 0], [0, 1, 2], [0, 2, 4], [0, 3, 6], [0, 4, 8]]

Example 6: Iterate over all items in a list of lists

The code converts a list of lists to a list of items
We call this flattening the list.

list_of_lists = [[8, 2, 1], [9, 1, 2], [4, 5, 100]]

# Standard loop form
flat_list = []
for row in list_of_lists:
    for col in row:
        flat_list.append(col)

print(flat_list)

# List comprehension:
flat_list = [item for sublist in list_of_lists for item in sublist]
print(flat_list)

Out:

[8, 2, 1, 9, 1, 2, 4, 5, 100]
[8, 2, 1, 9, 1, 2, 4, 5, 100]

98: Brief examples of applying lambda functions to lists, and filtering lists with list comprehensions, map and filter

These examples are intended as a reminder of how to use list comprehensions, map and filter. They are not intended to be an exhaustive tutorial.

Let’s start with a list of numbers, and we wish to:

1) Square all numbers
2) Find even numbers
3) Square all even numbers

That is where list comprehensions, map and filter come in. There is significant overlap between these methodologies, but here they are.

Define my list of numbers

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Square numbers with list comprehension

answer = [x**2 for x in my_list]
print (answer)
Out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Map a named lambda function to square the numbers

We use a one-line lambda function here, but a full function with define and return could also be used.

sq = lambda x: x**2
answer = list(map(sq, my_list))
print (answer)
Out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Map a lambda function directly to square numbers

answer = list(map(lambda x: x**2, my_list))
print (answer)
Out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Use a lambda function in a list comprehension

sq = lambda x: x**2
answer = [sq(x) for x in my_list]
print (answer)
Out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Filter a list with list comprehension to find even numbers

For even numbers x%2 will equal zero:

answer = [x for x in my_list if x%2 == 0]
print (answer)
Out:
[2, 4, 6, 8, 10]

Filter a list with a named lambda function

Full functions call also be used. The function (full or lambda must return True or False)

is_even = lambda x: x%2 == 0
answer = list(filter(is_even, my_list))
print (answer)
Out:
[2, 4, 6, 8, 10]

Filter a list with a lambda function applied directly

answer = list(filter(lambda x: x%2 ==0, my_list))
print (answer)
[2, 4, 6, 8, 10]

Combine squaring and filtering with a list comprehension

List comprehensions may filter and apply a function in one line. To get the square of all even numbers in our list:

answer = [x**2 for x in my_list if x%2 == 0]
print (answer)
Out:
[4, 16, 36, 64, 100]

Or we may apply lambda (or full) functions in both the operation and the filter ina list comprehension.

sq = lambda x: x**2
is_even = lambda x: x%2 == 0
answer = [sq(x) for x in my_list if is_even(x)]
print (answer)
Out:
[4, 16, 36, 64, 100]

Combine squaring and filtering with map and filter

filter and map would need to be used in two statements to achieve the same end. Here we will use named lambda functions, but they could be applied directly as above.

sq = lambda x: x**2
is_even = lambda x: x%2 == 0

filtered = list(filter(is_even, my_list))
answer = list(map(sq, filtered))
print (answer)
Out:
[4, 16, 36, 64, 100]