DEV Community

amdiamond107
amdiamond107

Posted on

List Comprehensions in Python

In Python, there are some instances where it can be pretty simple and straightforward for you to create a list of data, and then there are other instances where list creation can become a bit of a more cumbersome task -- and in these more challenging scenarios, we leverage what is called a list comprehensions to help us accomplish our goal.

List Comprehension essentially just offers a shorter syntax when you want to create a new list based on the values of an existing list.

Let's take a look at these two comparative examples directly below to further illustrate what we're getting at here...

Example: Let's say we are provided with a list of fruits, and tasked with creating a new list that is only comprised of the fruits from our original list containing the letter "a" within their names, then here are two ways to go about it...

*1. Without using list comprehension:
*

Image description

*2. Using list comprehension:
*

Image description

The power of list comprehension is evidently clear as our first example of code looks noticeably lengthier, clunkier, and more difficult to read/interpret than the second example of code.

Let's take a closer look at what this syntax in example two really means...

newlist = [expression for item in iterable if condition == true]

  • condition, which represents "a in x" in our example pictured above, acts as a filter that only accepts the items that valuate to true
  • iterable, which represents our original list of "fruit" in the example pictured above, can be any iterable object, like a list, tuple, set, etc.
  • expression, which represents the first of our two "x" values in the example pictured above, is the current item in the iteration, but is also the outcome, which you can manipulate before it ends up like a list item in the new list. The expression can also contain conditions as a way to manipulate the outcome to our liking.
  • item, which represents the second of our two "x" values in the example pictured above.

Additionally, when we return a new list using list comprehension, our old list remains unchanged.

No matter the instance, list comprehensions will always create new, complete lists that derive from a previous list, set, tuple, etc.

*Resources:
*

Top comments (0)