List comprehension is a clean, efficient syntax for processing list data in Python. An alternative to list comprehension is using
for loops, which can be quite verbose. Here I've outlined a number of common list comprehension patterns.
- Line #4: We apply an operation to each item in the list, resulting in list of the same size as the original.
- Line #7: We filter the list by adding a conditional statement in the comprehension, resulting in a smaller list than the original.
- Line #10-11: We conditionally apply an operation to each item in the list.
- Line #14: We perform nested list comprehension, producing a list of lists.
- Line #23: We again perform nested list comprehension, this time to flatten our list of lists.
Trey Hunner has a great blog post that goes into more details about list comprehensions.