×

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known as List Comprehension. To achieve the required result, it follows the form of the mathematical set-builder notation, this form is different from the filter and map functions.

In Python, the expressions are contained in brackets and all these come under the domain of Python list comprehension. For creating a new list based on the values ofthe previously existing list, a Python list comprehension provides shorter syntax.

Advantages of using a list comprehension

  • It is more efficient than loops, in both terms be it time efficiency or space efficiency.
  • Being space efficient, it requires fewer lines of code.
  • Since, it does not use loops, it simply converts them to formulas.

Syntax for List Comprehension:

name_of_list = [ element for element in previous_list if condition (if required)]

Examples of Python list comprehension

Example 1: Using iteration with list comprehension

# Using list comprehension to iterate through the loop
new_list=[ elementforelementin[1, 2, 3, 4, 5, 6, 7, 8]]
 
# Printing list using list comprehension
print(new_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Example 2: Using list comprehension to print the list of even numbers

# Using list comprehension and using if-condition
new_list=[eleforeleinrange(11) ifele%2==0] 
# Printing list using list comprehension
print(new_list)

Output:

[0, 2, 4, 6, 8, 10]

Example 3: Using list comprehension to print a matrix

mtrx=[[yforyinrange(4)] forxinrange(4 )]
# Printing a matrix created using the list comprehension
print(mtrx)

Output:

[[0, 1, 2, 3], [0, 1, 2, 3],  [0, 1, 2, 3], [0, 1, 2, 3]]

For loop vs. List Comprehension

There are different methods that we can use to iterate through a list. First, let us have a look at the “for loop” for iterating a loop.

Example:

# Creating an empty list
lst=[]
 
# Traditional approach of iterating
foriin'Java T Point':
    lst.append(i)
 
# Returning an appended list
print(lst)

Output:

['J', 'a', 'v', 'a', '', 'T', '', 'P', 'o', 'i', 'n', 't']

The above-given approach is traditional to iterate over a list, tuple, string, etc. List comprehension also does a similar task but in an easier way and makes the code smaller too.

This method first converts the traditional approach for iteration to a simple formula, therefore making it easy to use. It converts multi-line code used for looping to a single-line formula.

Example of a list comprehension to iterate over a tuple, list, string, etc.:

# Using list comprehension to iterate through the loop
new_list=[ elementforelementin'Java T Point'
 
# Printing list using list comprehension
print(new_list)

Output:

['J', 'a', 'v', 'a', '', 'T', '', 'P', 'o', 'i', 'n', 't']

Time analysis in Loop and List Comprehension

As discussed earlier, list comprehension is time and space efficient, i.e., it takes less time and space as compared to the traditional looping method. Normally, they are written on a single line.

Example:

# Import time module, as it will be required to check the time
#taken by these two methods
importtimeas tm
 
 
# Defining the function to implement the for loop
defforLp(n):
    rslt=[]
    forxinrange(n):
        rslt.append( x**2)
    returnrslt
 
 
# Defining the function to implement thelist comprehension
deflst_cmp(n):
    return[a**2forainrange(n)]
 
 
# Driver code to call functions created
 
# Calculating the time taken by theforloop()
start=tm.tm()
forLp(10**6)
end =tm.tm()
 
# Printing the time taken by the forloop()
print('Time taken by the for loop:', round(end-start, 2))
 
print('\n')


# Calculating the time taken by the list comprehension
start=tm.tm()
lst_cmpre(10**6)
end =tm.tm()
 
# Displaying the time taken by the list comprehension
print('Time taken by the list comprehension:', round(end-start, 2))

Output:

Time taken by the for loop: 0.27
Time taken by the list comprehension: 0.25

After observing the output of the above code, we can see that list comprehension is quite faster than loops.

Nesting in List Comprehensions

Nested list comprehensions are just like nested loops, when a list comprehension is within another list comprehension, it is said to be nested list comprehension. Below are two examples to show nested loops and nested list comprehension:

Example 1:

matrixx=[]
 
forxinrange(4):
 
    # Append an empty sublist inside the list
    matrixx.append([])
 
    foryinrange(4):
        matrixx[x].append( y )
 
print(matrixx)

Output:

[[0, 1, 2, 3], [0, 1, 2, 3],  [0, 1, 2, 3], [0, 1, 2, 3]]

Example 2:

# Nested list comprehension
matrix =[[j forj inrange(4)] foriinrange(4)]
 
print(matrix)

Output:

[[0, 1, 2, 3], [0, 1, 2, 3],  [0, 1, 2, 3], [0, 1, 2, 3]]

Lambda and List Comprehensions

Lambda functions are also like list comprehensions, they too help in making the code shorter. When list comprehensions are used with lambda functions, it forms an efficient combination.

Below are the examples for showing the use of lambda functions, and list comprehension for printing a table of 10:

Example 1: Printing a table of 10 using iteration

# Using iteration to print table
table=[]
 
forainrange(1, 11):
    table.append( a*10)
 
print( table)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Example 2: Printing a table of 10 using the list comprehension only

table=[a*10forainrange(1, 11)]
 
print( table)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Example 3: Printing a table of 10 using a combination of lambda and list comprehension

# Using combination to print a table of 10
table=list(map(lambdaa: a*10, [aforainrange(1, 11)]))
 
print( table)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Conditionals in List Comprehension

The conditional statements can also be used with list comprehension, by doing this we can create a list with the help of range( ), operators, etc.,and also apply required conditions using the else-if statements.

Key Points

  • List Comprehension is one of the most efficientways to construct and describe lists based on existing lists.
  • List Comprehension results in a simpler and more lightweightas compared to the standard loops and functions used to create lists.
  • Using List Comprehensions results in short code, which makes the code more user-friendly.
  • You can easily rewrite the list comprehension using the forloop. But it is not possible to rewrite the for loop in the context of List Comprehension

Following are the examples showing the use of list comprehension in multiple fields

Example 1: Using If-else for list comprehension in Python

list=["Even no"ifa%2==0
       else"Odd no"forainrange(8)]
print(list)

Output:

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

Example 2: Using nested if for list comprehension in Python

list=[aforainrange(100)
       ifa%5==0ifa%10==0]
print(list)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90]

Example 3: Printing square of numbers from 1 to 15

# Using list comprehension to get squares of numbers from 1 to 15
sq=[n**2forn inrange(1, 16)]
 
# Printingsquares of numbers from 1 to 15
print(sq)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]

Example 4: Transposing a 2-D matrix

# Creating a matrix
mat =[[10, 20, 30],
       [40, 50, 60],
       [70, 80, 90]]
 
# Transposing matrix
mat_tr=[[x[y] forxinmat] foryinrange(len(mat[0]))]
 
print(mat_tr)

Output:

[[10, 40, 70], [20, 50, 80], [30, 60, 90]]

Example 5: Converting the case of every character in the string

# Creating a string
str ='Java T Point'
 
# Toggle case of each character
lst=list(map(lambdaa: chr(ord(a) ^ 32), str))
 
# Printing converted list
print(lst)

Output:

[‘j’, ‘A’, ‘V’, ‘A’,  ‘\x00’, ‘t’, ‘\x00’, ‘p’, ‘O’, ‘I’, ‘N’, ‘T’]

Example 6: Returning the sum of all odd elements present in a list

# Explicit function
defoddSum(n):
    sum=0
    foriinstr(n):
        sum =sum+int(i)
    returnsum
 
 
# Creating a list
lst=[36, 11, 56, 94, 67, 87]
 
# Using the function on odd elements of the list
Nw_lst=[oddSum(i) foriinlstifi&1]
 
# Returning a new list
print(nw_lst)

Output:

[2, 13, 15]

Related Topics

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Spotify API in Python

The application programming interface is referred to as API. In essence, an API serves as a layer of communication or, as the name suggests, an interface that enables systems to...

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

GUI to Shut down, Restart and Logout from the PC using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

4 minutes read.