Python: List Comprehension

It is consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. It is used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. It requires fewer line of code. As compared to loops it is more time efficient and space efficient.

Syntax:

newList = [ expression(element) for element in oldList if condition ]

List Comprehension vs Loops

List comprehension is a single line code. By using for loop we can iterate in the same way but List comprehension does the same task and also makes the program more simple. It is an elegant way to define and create lists based on existing lists. It is more efficient both computationally and in terms of coding space and time than a for loop.

Using Loop:

my_list = []
for character in 'ProgramsBuzz':
    my_list.append(character)
    
print(my_list)  

Output: ['P', 'r', 'o', 'g', 'r', 'a', 'm', 's', 'B', 'u', 'z', 'z']

Using List Comprehension:

my_list = [character for character in 'ProgramsBuzz']
print(my_list)

Output: ['P', 'r', 'o', 'g', 'r', 'a', 'm', 's', 'B', 'u', 'z', 'z']

List Comprehensions and Lambda

There are various in-built function which can create and modify lists in less lines of code.

Lambda Expressions are nothing but shorthand representation of Python functions. Using list comprehensions with lambda creates an efficient combination.

letters = list(map(lambda x: x, 'python'))
print(letters)

Output: ['p', 'y', 't', 'h', 'o', 'n']

Nested List Comprehension

It is similar to nested for loop ,nested list comprehensions are nothing but a list comprehension within another list comprehensions.

matrix = []
for i in range(4):
    matrix.append([])
    for j in range(3):
        matrix[i].append(j)
       
print(matrix)

Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

Key Points

  •  It is an elegant way to define and create lists based on existing lists.
  • we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.
  • Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.
  • Comprehension of the list is an effective means of describing and constructing lists based on current lists.
Tags