21  List Comprehensions

When we perform mapping and filtering operations, we see these techniques involve a long-way list looping technique, which may span multiple lines.

A list comprehension is a powerful Python technique that allows us to perform mapping and/or filtering operations using a succinct one-liner syntax.

For the examples below, we will consider this simple list of numbers:

my_numbers = [1, 2, 3, 4, 5, 6, 7]
print(my_numbers)
[1, 2, 3, 4, 5, 6, 7]

21.1 List Comprehension for Mapping

Mapping, the long way:

my_numbers = [1, 2, 3, 4, 5, 6, 7]

transformed_nums = []

for n in my_numbers:
    transformed_nums.append(n * 100) # MAPPING

print(transformed_nums)
[100, 200, 300, 400, 500, 600, 700]

Mapping, the short way, using a list comprehension (equivalent):

my_numbers = [1, 2, 3, 4, 5, 6, 7]

# NEW_LIST = [VALUE_TO_COLLECT for ITEM in EXISTING_LIST]

transformed_nums = [n * 100 for n in my_numbers]
print(transformed_nums)
[100, 200, 300, 400, 500, 600, 700]

21.2 List Comprehension for Filtering

We optionally add an if clause to also implement filtering:

Filtering, the long way:

my_numbers = [1, 2, 3, 4, 5, 6, 7]

matching_nums = []

for n in my_numbers:
    if n > 3: # FILTER CONDITION
        matching_nums.append(n)

print(matching_nums)
[4, 5, 6, 7]

Filtering, the short way, using a list comprehension (equivalent):

my_numbers = [1, 2, 3, 4, 5, 6, 7]

# NEW_LIST = [VALUE_TO_COLLECT for ITEM in EXISTING_LIST if CONDITION]

matching_nums = [n for n in my_numbers if n > 3]
print(matching_nums)
[4, 5, 6, 7]

21.3 List Comprehension for Mapping and Filtering

We can mix and match techniques to perform both mapping and filtering, as desired:

Filtering and mapping, the long way:

my_numbers = [1, 2, 3, 4, 5, 6, 7]

matching_nums = []

for n in my_numbers:
    if n > 3: # FILTER CONDITION
        matching_nums.append(n * 100) # MAPPING

print(matching_nums)
[400, 500, 600, 700]

Filtering and mapping, the short way, using a list comprehension (equivalent):

my_numbers = [1, 2, 3, 4, 5, 6, 7]

new_nums = [n * 100 for n in my_numbers if n > 3]
print(new_nums)
[400, 500, 600, 700]

Hopefully these examples help you pick up the patterns, and get comfortable using list comprehensions to process data in a variety of ways.