Python List Comprehension

Filed Under: Python

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.


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

  • 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


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

Python List Comprehension, list comprehension python, lambda, python dictionary 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.


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[0])+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[0])+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.

References: Wikipedia

Comments

  1. Moises says:

    Greeat Article and tutorial!
    I would like to add the use of ‘if – else’ in a list comprehension.

    For the example you gave us for the nested list comprehension, if you add a single caracter word like ‘cat is not a dog’, the ‘a’ will be ignore, due to the if.
    Of course we can achive the addition of the ‘a’ using word.capitalize() as @Parigyan recommend and removing the if.

    Another way of doing that is using if else in a comprehension, you can do that with a simple reordering of the elements in the comprehension. e.g.

    list_string = [‘maNgo’, ‘BaNaNa’, ‘PythoN iS Love’, ‘Cat iS not a doG’]
    correct_case = [str.upper(word[0]) + str.lower(word[1:])
    if len(word) > 1 else word
    for word in sum([sentence.split() for sentence in list_string], [])
    ]
    // will get [‘Mango’, ‘Banana’, ‘Python’, ‘Is’, ‘Love’, ‘Cat’, ‘Is’, ‘Not’, ‘a’, ‘Dog’]

    Hope is helpfull
    And, again, great tutorial, thanks a lot!

  2. Parigyan says:

    Great article! However I would like to point out a built in function.
    Instead of

    // str.upper(word[0])+str.lower(word[1:]) //

    we can simply write or replace the above line with

    // word.capitalize() //

  3. Vijay says:

    I dont understand what is the need for empty list(square bracket) in the below sum statement.
    words = sum(list_of_list, [])

    How does sum() function works for list?

    1. Parigyan says:

      Actually the {} specified here creates a list. If you wanted to create a tuple () parenthesis would be right choice.

  4. shuryansh says:

    great tutorial…helping me a lot…. thanks a lot for this good work

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages