×

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 Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

To Do GUI Application 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...

3 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

AX Contour in Python

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.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Find key from value in dictionary python

Python: Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a...

5 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.