= [1, 2, 3, 4, 5, 6, 7]
my_numbers print(my_numbers)
[1, 2, 3, 4, 5, 6, 7]
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:
= [1, 2, 3, 4, 5, 6, 7]
my_numbers print(my_numbers)
[1, 2, 3, 4, 5, 6, 7]
Mapping, the long way:
= [1, 2, 3, 4, 5, 6, 7]
my_numbers
= []
transformed_nums
for n in my_numbers:
* 100) # MAPPING
transformed_nums.append(n
print(transformed_nums)
[100, 200, 300, 400, 500, 600, 700]
Mapping, the short way, using a list comprehension (equivalent):
= [1, 2, 3, 4, 5, 6, 7]
my_numbers
# NEW_LIST = [VALUE_TO_COLLECT for ITEM in EXISTING_LIST]
= [n * 100 for n in my_numbers]
transformed_nums print(transformed_nums)
[100, 200, 300, 400, 500, 600, 700]
We optionally add an if
clause to also implement filtering:
Filtering, the long way:
= [1, 2, 3, 4, 5, 6, 7]
my_numbers
= []
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):
= [1, 2, 3, 4, 5, 6, 7]
my_numbers
# NEW_LIST = [VALUE_TO_COLLECT for ITEM in EXISTING_LIST if CONDITION]
= [n for n in my_numbers if n > 3]
matching_nums print(matching_nums)
[4, 5, 6, 7]
We can mix and match techniques to perform both mapping and filtering, as desired:
Filtering and mapping, the long way:
= [1, 2, 3, 4, 5, 6, 7]
my_numbers
= []
matching_nums
for n in my_numbers:
if n > 3: # FILTER CONDITION
* 100) # MAPPING
matching_nums.append(n
print(matching_nums)
[400, 500, 600, 700]
Filtering and mapping, the short way, using a list comprehension (equivalent):
= [1, 2, 3, 4, 5, 6, 7]
my_numbers
= [n * 100 for n in my_numbers if n > 3]
new_nums 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.