Python List Comprehension (Syntax & Examples) – Nested List Comprehension Python

Free Python courses with 57 real-time projects - Learn Python

Previously, we discussed Lists in Python. In this tutorial, we’ll discuss what is Python list comprehension and how to use it?

Along with this, we will learn syntax, list comprehension vs lambda expression in Python3. Along with this, we will study conditionals and nested list comprehension in Python Programming Language.

So, let’s begin the Python list comprehension Tutorial.

Python List Comprehension

Python List Comprehension with Syntax and Examples

What is Python List Comprehension?

To get Python list comprehensions back into memory, we’ll take a quick example.

Suppose you want to take the letters in the word ‘anxiety’, and want to put them in a list. Remember that a python string is iterable.

Using a for loop, you would:

>>> mylist=[]
>>> for i in 'anxiety':
          mylist.append(i)
>>> mylist

Output

[‘a’, ‘n’, ‘x’, ‘i’, ‘e’, ‘t’, ‘y’]

But with a Python list comprehension, you can do this in one line:

>>> [i for i in 'anxiety']

Output

[‘a’, ‘n’, ‘x’, ‘i’, ‘e’, ‘t’, ‘y’]

Now that we’ve got your interest, we’ll dig a little deeper.

Syntax of List Comprehension in Python

For a python list comprehension, we use the delimiters for a list- square brackets.

Inside those, we use a for-statement on an iterable (a list, here). We’ll take an example.

>>> [i*2 for i in {3,1,2}]

Output

[2, 4, 6]

Here, we return twice of every value in the set {3,1,2} into a new list.

So we guess we can state the syntax for a Python list comprehension as follows:

[expression for item in list]

Note that not every loop has an equivalent list comprehension in Python.

Python List Comprehension vs Lambda Expression

Something about this syntax leaves us nostalgic. Remember when we learned about python lambda expressions in an earlier lesson?

A Python 3 lambda expression returns a certain expression’s value which it calculates using values of the arguments it receives.

Let’s create a list from a set using the list comprehension syntax.

>>> myset={3,1,2}
>>> makelist=lambda i:list(i)
>>> mylist=makelist(myset)
>>> mylist

Output

[1, 2, 3]

Here, we first took a set {3,1,2}. Like you’re aware by now, it rearranges itself as {1,2,3}. Then, we defined a lambda function, and stored it in the variable ‘makelist’.

This lambda function takes a value, converts it into a list, and returns it. Finally, we called makelist on the set myset, and stored it in the variable mylist, which now holds a list.

>>> type(mylist)

Output

<class ‘list’>

To do this using the map function instead, we write the following code:

>>> list(map(lambda i:i,myset))

Output

[1, 2, 3]

This code first takes a lambda expression: For each value i, it returns i and maps this on each value in the set myset. Next, it converts this into a python list and prints it.

A list comprehension’s advantage over a lambda function is that it is more readable. Try reading both, and see for yourself.

Conditionals in Python List Comprehension

So far, you know that we use a for-statement to declare our intentions.

But did you know that it is possible to add a condition to this?

This will add only those items to the list that meet the condition (for which the condition is True).

>>> [i for i in range(8) if i%2!=0]

Output

[1, 3, 5, 7]

This code takes the values in range(8), i.e., 0 to 7, and adds the odd values to a list.

a. Nested Conditionals

With a Python list comprehension, it doesn’t have to be a single condition; you can nest conditions. Here’s an example.

>>> [i for i in range(8) if i%2==0 if i%3==0]

Output

[0, 6]

Let’s see how this works. For integers 0 to 7, it first filters out the elements that aren’t perfectly divisible by 2.

For the remaining elements, it keeps only those that are divisible by 3. Finally, it stores these elements in a list, and prints it out.

Remember, this is a nested conditional, not an AND operation of two conditions.

b. if..else in List Comprehension in Python

You can also use an if-else in a list comprehension in Python. Since in a comprehension, the first thing we specify is the value to put in a list, this is where we put our if-else.

>>> ["Even" if i%2==0 else "Odd" for i in range(8)]

Output

[‘Even’, ‘Odd’, ‘Even’, ‘Odd’, ‘Even’, ‘Odd’, ‘Even’, ‘Odd’]

This code stores in a list, for each integer from 0 to 7, whether it is even or odd.

Try using different conditions with this one, and tell us in the comments.

Nested List Comprehension in Python

Finally, in this tutorial, we will end by discussing how to use a Python list comprehension for a nested for-loop.

Let’s take some code to print the tables of numbers 7 and 8. Using regular for-loops, we’d write the following code:

>>> for i in range(7,9):
        for j in range(1,11):
               print(f"{i}*{j}={i*j}")

Output

7*1=77*2=147*3=21

7*4=28

7*5=35

7*6=42

7*7=49

7*8=56

7*9=63

7*10=70

8*1=8

8*2=16

8*3=24

8*4=32

8*5=40

8*6=48

8*7=56

8*8=64

8*9=72

8*10=80

To do this using a python list comprehension, however, we use the following code:

>>> [[i*j for j in range(1,11)] for i in range(7,9)]

Output

[[7, 14, 21, 28, 35, 42, 49, 56, 63, 70], [8, 16, 24, 32, 40, 48, 56, 64, 72, 80]]

We used the for-loop for j as the inner comprehension, because it is the inner loop in the previous code.

So, this was all about Python List Comprehension Tutorial. Hope you like our explanation.

Python Interview Questions on List Comprehension

  1. What is a Python list comprehension?
  2. How Python list comprehension is useful?
  3. How does list comprehension work in Python?
  4. Give an example of Python list comprehension
  5. Are list comprehensions faster in Python?

Conclusion

Now that you do better with python list comprehensions, we hope you’ll make good use of it for speed and readability.

However, it makes no sense to write a very long and complicated list comprehension.

Also, you can write a for-loop for every list comprehension in python, but not you can’t write list comprehensions for very complex for-loops.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

6 Responses

  1. Ruben J. Leon says:

    For list comprehensions, why is the IF syntax so different from the IF/ELSE syntax?

    “IF” statement:
    [ EXPR for VAR in SEQUENCE if CONDITION ]

    Notice the if condition above comes at the end.

    “IF / ELSE” statement:
    [ on_true if expression else on_false for VAR in SEQUENCE ]

    Notice the if/else now come before the for statement.
    Isn’t the If/Else statement in this list comprehension actually the ternary operator?

    • DataFlair says:

      Yeah, the sytax is similar to teranary operator here.

      Yes, the syntax is different and it make the code more readble. Hope you have understood the explaination.

  2. Sudip Ray says:

    Really helpful about the conditional statement within loop in list comprehension. Thanks a ton.

  3. shririsha Adlur says:

    got to know lot of things while moving with the topics thank you so much for your explaination and had a cleared version of the python now

Leave a Reply

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