Previously in this Python tutorial, we have already learned what Python lists are and how to use them. We have also understood list comprehension Python. In this section, we will go deep into list comprehension Python and understand why we need it. Following is the list of all topics that we will cover in this section:
Some of the programming languages have a syntactic construct called list comprehension for creating lists on the basis of existing lists. Python is one such language. In other words, list comprehensions are used for converting one list into another list or creating a new list from other iterables.
A list comprehension consists of:
Let’s take a brief look over Python lists before starting with Python list comprehensions.
Python list is a compound data type in Python where we can group together various values. These values need not be of the same type; we can combine Boolean, string, and integer values together and save them as lists.
The syntax of Python lists consists of two square brackets inside of which we define our values separated by commas. These values can be of any data type.
The syntax of List comprehension Python consists of square brackets inside of which we write an expressions followed by a “for clause” and then by more “for or if clauses” as needed.
The expressions can be anything. We can input any kind of object in the lists.
When compared to a normal Python Lists syntax, the above syntax is equivalent to
The resultant is a new list that is created after the evaluation of the expression in accordance with the ‘for’ and ‘if’ clauses provided after the expression.
Thus we can replace the following code for defining and creating a list in Python:
Following is the equivalent code in List Comprehension Python to obtain the same result:
List comprehension is an elegant and concise way of creating a list in Python. There are many benefits of using Python List comprehensions and the most basic benefit can be seen from the syntax alone. We reduced three lines of code into one liner. Not just that but the code in Python List comprehension is much faster also. With Python List comprehension, instead of having to resize the list on runtime, python will now allocate the list’s memory first, which makes it faster in this case.
Moreover, the code using Python List comprehension is considered to be more fitting in the guidelines of Python making it more Pythonic in nature.
Now that we know the syntax of Python List comprehensions, let try out some examples.
Example 1: Let’s start by creating a simple list.
Example 2: Now let’s create a list using “for” clause in list comprehension.
Example 3: Let’s create a new list by making some changes in an already existing list.
In the above code block, the new list is named new_multiplied_list, and it is obtained by multiplying every element of the old list, which is named as list1, with 2.
Example 4: Now let’s create a new list containing the first letters of every element in an already existing list.
Whenever we want to repeat a block of code for a fixed number of times, the first way of doing it is using ‘for loops’. List comprehensions are also capable of doing the same that too with a better approach than for loops, since list comprehensions are more compact. Hence, it provides a very good alternative to for loops.
Let’s take an example here. Say, we want to separate the letters of a word and create a list containing those letters.
The code block for the same in case of using for loop will be:
We can obtain the same result using List Comprehension with lesser number of code lines as shown below:
While using Python list comprehensions, we don’t necessarily need a list to create another list. We can use strings as well, and list comprehension will identify it as a string and work on it as a list. In the above example of list comprehension code block, Intellipaat is a string, not a list.
In Python, we also use Lambda functions to modify and manipulate lists. Lambda functions are also known as anonymous functions. Lambda functions are usually used with various built-in functions such as map() filter(), and reduce() to work on lists.
Let’s first see how we use map() with Lambda function to work on lists:
In the above block of code, we have used map() with lambda to create a list containing the letters of the string “intellipaat” separated by comas. The name of the list is the letters.
We can obtain the same result using Python List Comprehensions. The codes in Python List comprehensions are also more human readable and easier to understand.
Follow the following steps to write the equivalent Python List comprehension code:
So the final code using Python List Comprehension looks like:
Now that we know how we can use Python list comprehension as an alternative for the map() function combined with lambda, let’s now see how we can use Python list comprehensions as an alternative for the filter() function.
In the following code block, we have used filter() with lambda to filter out odd values from an existing list and save the filtered values in a new list.
The name of the new list in our example is new_list.
The same result can be obtained using Python List Comprehension as shown below:
As mentioned above, we can also write the lambda function codes with the reduce() function to make the code short and more efficient using Python list comprehensions.
The following block of code is an example of reduce() with lambda:
Note: Recently, the reduce module was moved to the functools package, so If we are using Python 3, then we will have to import the reduce module from functools as shown in the above code block.
The resultant list contains the sum of all the elements of the list, list1.
The same result can be obtained using Python list comprehensions as shown below:
Note: Python list comprehensions only work with one variable, so the use of Y here is not allowed. Hence, to perform the above task, we can use an aggregation function, such as, sum().
We can also make use of conditional statements in list comprehensions to modify and manipulate lists. Let’s learn how to do that with the help of some examples. Here, we will use a mathematical function range() which defines the range that we want to use in our examples. It takes one integer as a parameter and the range starts from 0 to the number one less than the parameter provided. For example, range(20) will consider the range of numbers from 0 to
Example1: Using if statement in Python List comprehension
Example2: Using Nested IF with Python List Comprehension
In the above example, the first condition that the list comprehension checks is if x is divisible by 2, and then if the condition is met it encounters the other conditional statement and checks if x which was found to be divisible by 2 is also divisible by 5.
If both the conditions are met, only then x is appended to the list new_list.
Example3: Using if else statement with Python List comprehension
In the above example, the list comprehension checks all numbers starting from 0 to 9. If x is found to be divisible by 2, ‘x is even’ (where x is the respective number) is appended to the even_odd list. If the condition is not met, then the else statement is executed, and ‘x is odd’( where x is the respective number) is appended in the even_odd list.
Whenever we talk about nested lists, the first method to implement nested lists that comes to our mind is using nested loops. As we have already seen that Python list comprehension can be used as an alternative for loops, obviously it can also be used for nested loops. Let’s see how to do it with the help of an example.
Let’s say, we want to display the multiplication tables of 4, 5, and 6. Now using regular nested for loops, we would write the following code block to implement the same:
The output would be:
We can obtain the same result using Python list comprehension, and the code block used will be:
In the above example, we have used ‘for loop’ for y as the inner comprehension.
Python list comprehensions are found to be faster and more user-friendly than for loops and lambda functions. The speed and the readability are what that makes Python list comprehensions a favorable alternative for loops and lambda function. Mastering Python list comprehension can make our codes more efficient, faster, and shorter. While we have covered all main topics, along with examples, there is more to learn about Python. Want to gain in-depth knowledge and up-to-date study material? Check out this well-structured Python Certification Training Course by Intellipaat. This course will help master all main modules and packages in Python, web scraping libraries, lambda function, and more. Through this course, learn how to write Python codes for Big Data systems, such as Hadoop, and get plenty of hands-on exercises to practice and master Python.
Download Interview Questions asked by top MNCs in 2019?