Python List Comprehension With Examples

In our previous tutorial we learned about Python Sort List. In this tutorial we will learn about Python List Comprehension.

Python List Comprehension

Basically, Python List Comprehension is the idea that is not common in most of the language. It is basically used to generate a list of elements having some specific property. Moreover, Python List Comprehension make code smaller but effective. Let us consider the following code.

You will get output as

But you can shorten the previous code by Python List Comprehension. So the desired code will be

And you will get the same output

Basic Structure of Python List Comprehension

The basic structure consist of three parameters. On basis of these three parameter, python generated a new list. The parameters are given in the list below

  • Variable
  • Expression for output
  • Reference sequence
  • Predicate (Optional)

In this section, we are going to learn how to code using Python List Comprehension. Suppose you have a list of number. Now, you want to make a new list where only the immediate number of the even numbers of the previous list will exist. So the traditional code will be

The output of the following code will be

Pretty much large code, right? But you use Python List Comprehension, the code will be much short. And the code will be

As we said earlier, Python List Comprehension has three parameters. In the previous code we also used all the parameters. See the below picture. For better understanding, each parameters are colored differently

Python List Comprehension

So, that’s the structure for writing Python List Comprehension!

Using for Strings

So far we have seen examples of Python List Comprehension using numbers. You can do amazing things for String using Python List Comprehension. Suppose, you have a list of string. You want to do some modification, like

  • If the string is sentence, split it into words
  • Make case of all the words like: First letter is capital and rest of the letter is small

The following code will help you th understand the thing.

So, the output of the code will be

Making Nested List Comprehension

However, you can also use nested List comprehension. That means, you can use a list comprehension inside another list comprehension. For example, the previous example code can be written shorter using nested Python list Comprehension. Like this,

And the output will be

But the following code is not easily readable in many cases. So, nested Python List Comprehension is not recommended to use in every case though it make code short.

So that’s all about Python List Comprehension. Hope, you understand the topic. For any query, please use the comment box for help. We will help you.

References: Wikipedia

By admin

Leave a Reply