How to implement list comprehension in python

Introduction

List comprehension in python provides a concise way to create lists. It allows you to generate the list in just one line of code. It combines the for loop and the creation of new elements into one line and automatically appends each new element.

List Comprehension

For example, Lets assume that we want to create a list of squares (without implementing list comprehension):

squares = []
for i in range(10):
    squares.append(i**2)
print(f"Square value in the range of 10: {squares}")


Output:

Square value in the range of 10: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


We can do the same in more concise and readable format using list comprehension:


Equivalently,

squares = [i ** 2 for i in range(10)]
print(f"Square value of range 10: {squares}")

Output:

Square value of range 10: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note: A list comprehension in python consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses that follow it.

More Example on List Comprehension

Example:

Using for and if clause to find the repeated number in the list;

x = [1,2,4,7,3]
y = [8,9,4,7, 12]
num = [(i,j) for i in x for j in y if i==j]
print(f"Repeated number: {num}")

Output:

Repeated number: [(4, 4), (7, 7)]



Nested List Comprehensions

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension;

Example:

# Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:
matrix = [[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
        ]

# The following list comprehension will transpose rows and columns:
m = [[(row[i])for row in matrix] for i in range(4)] 
print(m)

Output:

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Which in turn is same as below without implementing a nested list comprehension.

Example:

matrix = [ [1, 2, 3, 4],
           [5, 6, 7, 8],
           [9, 10, 11, 12],
         ]
transposed = []
for i in range(4):
    transposed_row = []
    for row in matrix:
        transposed_row.append(row[i])
    transposed.append(transposed_row)
print(f"Transposed Matrix: {transposed}")

Output:

Transposed Matrix: [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]