Python Introduction

Python List Comprehension

The list is a mutable and ordered sequence of elements. If you are aware of any other languages, then you can compare lists to arrays in C and C++. The only difference is that you can store different data types in a single list while an array has to have all elements of the same data type. Let us learn about list comprehension python here. 

List Comprehension Python

Python is known for its various features that are provided to make sure that the code is more elegant and easier to write. One such tool that increases the functionality of the code is list comprehension.  

List comprehension Python

List comprehension python are a way through which you can create lists with the least amount of code. While coding, it is essential that you keep your code as concise as possible so that you can better understand it in the future. An extensive amount of code will make it look less professional and more redundant. 

List comprehensions are especially used when the elements in the list are to be included after a calculation. The elements of the list correspond to the result that is obtained from a certain calculation. Through the examples given later in this tutorial, you will come to understand how list comprehensions make your code look more sophisticated and are the perfect tool to save time while coding.  

List Comprehension vs For Loop in Python 

There are various ways a list can be created in Python. Usually, when lists are created, the easiest way to add elements to them is through for loop. The for loop keeps running and adding exempts to the list as long as the user wants it or until the maximum range of the list is reached. Here are the steps that are included in the process of creating lists through for loop. 

  1. Initiate the list. 
  2. Apply loop that iterates over the range of the elements included in the list. 
  3. Append each element at the end of the list. 

Reminder: append () method is used to add an element to the end of the list. Other methods such as insert () or extend () can be used as well, as per the requirement of the user. 

Here is an example code where a list is created that contains twice of the first ten natural numbers. The list is created using a for loop. 

                    

double = []

for x in range (10):

              double.append (2 * x)

print (double)

Here, the first line of code initiates the empty list. The for loop is iterated over 10 elements after which the elements are printed. Try for yourself to know what the output of the code will look like. 

Notice that using for loop takes 4 lines of code to create and add elements to the list. To shorten this, list comprehension can be used. The syntax of list comprehension Python is as follows. 

name of list = [expression for elements in the list]

The most essential elements that are included in list comprehension are as follows. 

  • Expression: This is an expression that returns a value. It can be the element of the list itself or even a method that can be used for lists. For the example that we are considering, the expression will be 2 * x. 
  • Element: These are the members of values that are to be stored in the list. 
  • List: The name of the list with its range is to be included here. In our example, it is range (10). 

Here is how the code will look like when we use list comprehension to initiate and create a list. 

                    

double = [ 2 * x for x in range (10)]

The meaning of the code is clear and can be understood by someone with minimal coding experience. It is also concise and looks elegant.   

List Comprehension vs Lambda Function 

List Comprehension Python

When it comes to conciseness, using the lambda function with the map () method can also enable you to create a list using a single line of code. However, the code is harder to understand as it uses a method. Here is our example list created using the lambda function. 

                    

double = list (map (lambda x: 2 * x, range (10)))

Here, the map () method passes an object and the object will be added to the list as an element. Notice that the code is not only difficult to understand but also for a more complex code, it can be harder to write. Thus, using list comprehension will be much more comprehensible and easier to use rather than the map () method with a lambda function.  

Conditionals in List Comprehension 

In a list comprehension Python, you can use a conditional statement to modify the existing list. The syntax is like follows.

name of the list = [expression for element in list (conditional statement)]

The conditional statement is beneficial as they allow list comprehension to filter values that are not required to be added to the list. You could also use filter () for this endeavour. Here is an example. 

                    

double = [2 * x for x in range (10) if x % 2 == 0]

print (double)

The output of the code will print twice the number of only even numbers. You can test it yourself. 

You can also nest IF conditional statement in list comprehension to filter the elements as per the requirement of the code. 

Nested Loops in List Comprehension 

There are cases when elements that are to be added to the list needs to be filtered with nested loops. One such example can be while working with the matrix. Loop comprehension allows nesting for loops in its expression. Here is an example. 

                    

matrix = [[0,1], [1,2], [2,3]]

transpose = [[row[x] for row in matrix] for x in range (2)]

print (transpose)

Test the code yourself and find the output of the code. To put things into perspective, here is how the code will look like if you use nested for loops without list comprehension. 

                    

transpose = []

matrix = [[0,1], [1,2], [2,3]]

for x in range (len (matrix [0])):

              transpose_row = []

              for row in matrix:

                             transpose_row.append (row[x])

              transpose.append (transpose_row)

print (transpose)

Examples:

1.Write a program that prints all the letters of a string using list comprehension Python

                    

letters = [letter for letter in “python”]

print (letters)

2.Create a list with elements that range from 1000 to 2000 with steps to 150 using list comprehension. 

                    

my_list = range (1000, 2000, 150)

new_list = [x for x in my_list]

print (new_list)

3.Use list comprehension to create a list that includes squares of each element already present in the list. 

                    

list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

list_2 = [ x ** 2 for x in list_1]

print (list_2)

4.Using list comprehension, construct a list of employees whose age is greater than 25 years from the dictionary that consists of the name of the employees with their age. 

                    

dict = {“Ram”: 23, “Suraj”: 25, “Sakshi”: 27, “Sonya”: 30}

list_1 = [x.upper () for x in dict if dict [x] > 25]

list_1 = []

print (list_1)

Key Points of Remember

  • List comprehension is a concise way to initiate and create lists in Python. 
  • List comprehension Python makes the code look more elegant and compact than using for loop or lambda function. 
  • List comprehension allows using if conditional statements, nested if conditions, and nested for loops to filter the elements that are to be added to the list. 
  • To make the code more user-friendly and comprehensible, list comprehension is the best way.

FAQs on List Comprehension Python

1. What is list comprehension in Python?

List compression is an advanced feature provided by Python that increases the functionality of the code and makes it look more elegant. It is used to create and initiate lists and apply filters or functions to a list of items. 

2. How do you write a list comprehension in Python?

List comprehension Python follows the general syntax is given below. 

name of the list = [expression for element in the list]

However, this syntax is incomplete as it does not completely utilise the functionality of the list compression feature. One should add the if conditional statement to the expression to the list compression. 

name of the list = [expression for element in the list if condition]

List comprehension is used instead of for loops and lambda function.      

3. Is list comprehension faster in Python?

As one can guess, as list comprehension Python only requires one statement, it will always be faster than the longer code that is used in for loop. However, it is only faster for simpler functions and codes. If the iterations performed for the elements of the list are necessarily more complex, then the time taken to compute the code will increase.     

4. What is the list comprehension equivalent for?

List comprehension is used in place of for loop to create a list. It works similarly to the for loop and lambda function with map () method but with lesser and sampler code lines. 

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.