In our previous tutorial we learned about Python Sort List. In this tutorial we will learn about Python List Comprehension.
Table of Contents
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.
word = "Python" letters =  for letter in word: letters.append(letter) print(letters)
You will get output as
['P', 'y', 't', 'h', 'o', 'n']
But you can shorten the previous code by Python List Comprehension. So the desired code will be
word = "Python" # shorten the code letters = [letter for letter in word] print(letters)
And you will get the same output
['P', 'y', 't', 'h', 'o', 'n']
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
- 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
reference = [1, 2, 3, 4, 5, 6] output =  for number in reference: if number % 2 == 0: # the number is even prev_num = number-1 # calculate previous number output.append(prev_num) # append to the list print(output)
The output of the following code will be
[1, 3, 5]
Pretty much large code, right? But you use Python List Comprehension, the code will be much short. And the code will be
reference = [1, 2, 3, 4, 5, 6] output = [(number-1) for number in reference if number % 2 == 0] print(output)
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
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.
list_string = ['maNgo', 'BanAna', 'PytHoN iS Love', 'Cat iS not doG'] # make the list of string to list of list of words list_of_list = [sentence.split() for sentence in list_string] print(list_of_list) words = sum(list_of_list, ) # make the list of list to a single list print(words) # print the list of word # modify the case correct_case = [str.upper(word)+str.lower(word[1:]) for word in words if len(word) > 1] # print the list of word with desired case print(correct_case)
So, the output of the code will be
[['maNgo'], ['BanAna'], ['PytHoN', 'iS', 'Love'], ['Cat', 'iS', 'not', 'doG']] ['maNgo', 'BanAna', 'PytHoN', 'iS', 'Love', 'Cat', 'iS', 'not', 'doG'] ['Mango', 'Banana', 'Python', 'Is', 'Love', 'Cat', 'Is', 'Not', 'Dog']
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,
list_string = ['maNgo', 'BanAna', 'PytHoN iS Love', 'Cat iS not doG'] correct_case = [str.upper(word)+str.lower(word[1:]) for word in sum([sentence.split() for sentence in list_string], ) if len(word) > 1] # print the list of word with desired case print(correct_case)
And the output will be
['Mango', 'Banana', 'Python', 'Is', 'Love', 'Cat', 'Is', 'Not', 'Dog']
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.