= [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:
Mapping, the long way:
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):
# 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]
We optionally add an if
clause to also implement filtering:
Filtering, the long way:
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):
We can mix and match techniques to perform both mapping and filtering, as desired:
Filtering and mapping, the long way:
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):
Hopefully these examples help you pick up the patterns, and get comfortable using list comprehensions to process data in a variety of ways.