How do list comprehensions in Python work?



In this article, we will learn list comprehensions and the working of list comprehensions in Python.

What are List Comprehensions?

Using a sequence or another list that we can loop through, list comprehensions enable us to swiftly generate new lists. In Python, an iterable is anything that can be looped over. A syntactic technique called list comprehension makes it possible to build new lists out of older ones. List comprehension is based on the loop (or "for" loop). Any list comprehension may be represented as a for loop, but when it is represented as an equal list comprehension in a single line, it looks to be really unique.

List Comprehension − As we all know that python is well know for it’s short syntax characteristics, List Comprehension uses shorter syntax that helps to create a new list that is based on the value of existing list.

Syntax

newlist = [ expression(element) for element in oldlist if condition ]

Advantages of List Comprehension

  • List Comprehension is more space and time efficient compared to loops.

  • less lines of code is required.

  • It Converts iterative statements into a formula.

  • When appending items to a list, list comprehensions perform considerably faster than for-loops.

  • List comprehensions are a great replacement for the built-in map and filter functions.

Iterating Through a List Using List Comprehension

Example

The following program iterates through a list using list comprehension and creates a new list −

# iterating through the list using loop and list comprehension to create new list
resultList = [element for element in [5, 10, 15, 20, 25]]

# printing the resultant list 1. How do list comprehensions in Python work?
print(resultList)

Output

[5, 10, 15, 20, 25]

Printing Odd Numbers Using List Comprehension

Example

The following program prints all the odd numbers below 20 using list comprehension −

# getting all the odd elements in a range of 20(excluded)
# using list comprehension
OddList = [element for element in range(20) if element % 2 != 0]

# printing all the odd numbers below 20
print(OddList)

Output

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Printing Matrix Using List Comprehension

Example

The following program prints the 3*3 matrix using list comprehension −

# creating matrix with 3 rows and 3 columns using list comprehension
inputMatrix = [[n for n in range(3)] for m in range(3)]

# printing the 3x3 matrix
print(inputMatrix)

Output

On executing, the above program will generate the following output −

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

Comparison between List Comprehension vs For Loop

Using For Loop

The following program creates a list of all the characters of the string using the for loop and append() function −

Example

# creating an empty list for storing resultant string characters
resultList = []
# input string
inputString = 'Tutorialspoint'
# traversing in each character of the
# input string using for loop(in a Traditional way)
for char in inputString:
   # appending corresponding string character to the resultant list
      resultList.append(char)
# printing the resultant list which is initialized above
print(resultList)

Output

['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']

We have iterated through a list, string, tuple, etc in the above code using the standard method. List comprehension performs same task and makes the program more readable.

Using For List Comprehension

List comprehensions are used for simplifying the traditional iteration approach. It does it by using the for loop by converting into a simple formula.

Example

The following program will demonstrate how to creates the same list of all the characters of the string using the list comprehension −

# iterating through each character in a string
# using list comprehension
resultList = [char for char in 'Tutorialspoint']

# printing the result list containing all the characters
# of a string passed
print(resultList)

Output

['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']

Nested List Comprehensions

A list comprehension within another list comprehension is called Nested List comprehensions

Example

The following program shows an implementation of the nested loop −

# creating an empty list for storing the result matrix
outMatrix = []
for m in range(3):
   # appending an empty sublist to the above-defined output tMatrix
   outMatrix.append([])
   for n in range(4):
   # appending corresponding element to the output Matrix
      outMatrix[m].append(n)
# printing the output matrix
print(outMatrix)

Output

On executing, the above program will generate the following output −

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

Implementing Nested Loop Using Nested List Comprehension

The same result can now be created in fewer lines of code by using nested list comprehensions.

Example

The following program creates the nested lists using the list comprehension −

# creating an empty list for storing the result matrix
# implementing nested loop using Nested list comprehension
# getting a 3*4 matrix
outMatrix = [[n for n in range(4)] for m in range(3)]
# printing the resultant 3*4 matrix
print(outMatrix)

Output

On executing, the above program will generate the following output −

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

Flattening a multi-dimensional list using List Comprehensions

Assume we need to flatten a 2D list. We can easily accomplish this with List Comprehension and a sublist.

Example

The following program shows an implementation of the nested loop −

# input 2-dimensional(2D) list
input2DList = [[4, 6, 1], [2, 5, 3], [0, 1, 2]]
# flattening to a one-dimensional list
flattenList = [value for sublist in input2DList for value in sublist]
# printing the flattened list
print(flattenList)

Output

On executing, the above program will generate the following output −

[4, 6, 1, 2, 5, 3, 0, 1, 2]

Conclusion

This article has taught us what list comprehensions are and their advantages. In order to understand how to list comprehension works, we used a number of examples. We've also contrasted several methods for utilizing list comprehensions to reduce code size. To compare with and without list comprehensions code, we used a few comparison samples.


Advertisements