= [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:
[100, 200, 300, 400, 500, 600, 700]
Mapping, the short way, using a list comprehension (equivalent):
We optionally add an if
clause to also implement filtering:
Filtering, the long way:
[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:
[400, 500, 600, 700]
Filtering and mapping, the short way, using a list comprehension (equivalent):
[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.