Patternite Logo

List comprehension in Python


An overview of several common list comprehension patterns in Python


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.

  1. Line #4: We apply an operation to each item in the list, resulting in list of the same size as the original.
  2. Line #7: We filter the list by adding a conditional statement in the comprehension, resulting in a smaller list than the original.
  3. Line #10-11: We conditionally apply an operation to each item in the list.
  4. Line #14: We perform nested list comprehension, producing a list of lists.
  5. 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.

Profile picture for duncster

| edited

Patternite © 2022

Patternite Logo