Skip to main content

Python List Comprehension

Python Lists are datatypes in Python which allows us to store data in an ordered sequence of elements.

This chapter will discuss the List Comprehension.

What is List Comprehension in Python?

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

For example, make a list with each element multiplied by 10:

mult = [10 * x for x in range(10)]
print(mult) # [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

and this code is equivalent to:

mult = []
for x in range(10):
mult.append(10 * x)
print(mult)

How to use List Comprehension

The syntax for list comprehension is:

new_list = [expression for item in iterable if condition]

where:

  • The expression is the current item in the iteration, but it is also the result, which can be manipulated before it ends up as a list item in the new list
  • The iterable can be any iterable object, like a list, tuple, set etc.
  • The condition is like a filter that only accepts the items that valuate to True.
note

The return value is a new list, leaving the old list unchanged.

Conditionals in List Comprehension

You can add one or more conditions to the List Comprehension.

If Conditional List Comprehension

Example with only one if in the list comprehension, where the new list will be populated only with even numbers from the original list.

numbers = [ x for x in range(20) if x % 2 == 0]
print(numbers)

Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Multiple if Conditional List Comprehension

Example with multiple if in list comprehension where only elements divisible by 2 and 5 are added to the new list:

numbers = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(numbers)

Output

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

Multiple if-else in the List Comprehension are equivalent to and operation where both conditions have to be true.

if-else Conditional List Comprehension

Example with if-else in Set Comprehension where elements divisible by 2 have the value even while others have the value odd.

numbers = ["Even"if i%2==0 else "Odd"for i in range(20)]
print(numbers)

Output

['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
note

if-else in the List Comprehension are equivalent to if-else flow control.

Nested List Comprehension

Nested List can be created adding list comprehensions to list comprehensions.

For example, calculating the transpose of a matrix requires a nested loop

transposed = []
matrix = [[1, 2, 3], [4, 5, 6]]

for i in range(len(matrix[0])):
transposed_row = []

for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)

print(transposed)

Output

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

This example can be rewritten using two nested list comprehensions in this way:

matrix = [[1, 2], [3,4], [5,6]]
transposed = [[row[i] for row in matrix] for i in range(2)]
print(transposed)

Output

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

Nested loops in list comprehension do not work like normal nested loops. In the previous program, for i in range(2) is executed before row[i] for row in matrix. Therefore, at first a value is assigned to i and then the element directed by row[i] is added to the transpose variable.

List Comprehension vs Lambda function

List comprehensions are not the only way to work on lists. Various built-in functions and lambda functions can create and modify lists in fewer lines of code.

For example, define a lambda function to create a list from string 'Tutorial':

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

Output

['T', 'u', 't', 'o', 'r', 'i', 'a', 'l']
note

List comprehensions are usually more human-readable than lambda functions.