Python List Comprehension (Syntax & Examples) – Nested List Comprehension Python
Master Python with 70+ Hands-on Projects and Get Job-ready - 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.
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
But with a Python list comprehension, you can do this in one line:
>>> [i for i in 'anxiety']
Output
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
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
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
To do this using the map function instead, we write the following code:
>>> list(map(lambda i:i,myset))
Output
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
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
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
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
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
- What is a Python list comprehension?
- How Python list comprehension is useful?
- How does list comprehension work in Python?
- Give an example of Python list comprehension
- 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.
Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google
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?
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.
Really helpful about the conditional statement within loop in list comprehension. Thanks a ton.
We are glad that our readers are liking DataFlair Tutorials. Stay with us for learning more.
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
Thanks for liking Python Tutorials. We are sure you will not like to miss Free Python Course by DataFlair