How to Create a List Comprehension in Python 


               


How to Create a List Comprehension in Python



Python


In this article, we show how to create a list comprehension in Python

What is a list comprehension?

A list comprehension in Python is a way of writing condensed code to execute a function on every item in a list.

With a list comprehension, it is so much easier to execute a function on every item of a list.

Let's say, we want to find the square of a number of a list.

With a list comprehension, it is done in a single line.

This is shown in the code below.



You can see how simple this code is.

So we have our list, list1, equal to numbers 1 through 5.

We then create a variable, squared and set it equal to a list comprehension.

Now in the list comprehension, we specify first the operation we want to perform on each item of the list followed by the keyword for, followed by the variable we created that specifies eacah item, followed by in list1.

In this operation, we are finding the square root for each number in the list.

We then call the variable, squared, which returns the list now with each number squared.

This is a list comprehension in Python.

You use a list comprehension whenever you want to perform an operation on each item of a list. It simplifies the process greatly.

If you did not use a list comprehension and instead use a for loop to do it, which of course you can, it would look like the code shown below.



You can see this code is a lot more verbose than a list comprehension.

Once you get used to list comprehensions in Python, you wouldn't want to run code like the above anymore.

Any time you want to perform an operation on every item of a list, you will prefer to use list comprehensions.

So below are more examples of list comprehensions.

Below is the a list comprehension that finds the cubed



Below is a list comprehension that finds the square root of every number in a list



And this is what list comprehensions are and how they can be created in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...