Python List Comprehensions

A special syntax form in the Python language is the list comprehension. List comprehensions allow programmers to make their code more compact and (sometimes) harder to read if they push the comprehensions too far! The syntax consists of an expression in square brackets to create a new list. In order to show the beauty of the list comprehension, I will present a solution (using list comprehensions) to a common problem: iterating through a list of items and then creating a second list that contains data from the first list that satisfies a particular condition.

Suppose we have a list of numbers that range from 0 up to 20. We want to create another list from this range that only contains the numbers that are multiples of 2. The code to do this would normally look like this:

>>> numbers = range(0,21)
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

>>> b = [] # We create an empty list that will hold the multiples of 2
>>> for number in numbers:
        if number % 2 == 0:

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

The code uses to for loop to iterate through each number in the numbers list and an if statement to test if the number is a multiple of 2. If it is, the number is appended to the b list. Let’s do the same thing using a list comprehension:

>>> numbers = range(0, 21)
>>> b = [number for number in numbers if number % 2 == 0]

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

Wow! In the second example, we managed to code a solution to the problem on only one line. The result is created in a single step. This syntax is a looks a little foreign at first so let’s break it down.
The statement on line 2 creates a list, which is explains the square brackets. The “number” variable is what we want to return after each iteration of the loop on the right. The “for” loop goes through each number in numbers and checks if each number is a multiple of 2 using the modulus operand. If “number” is a multiple of 2, it is appended to “b”

The first and middle parts of the list comprehension are straight forward, but the last part, the if, is odd, I know. The only way to get this is to commit a few brain cells to remembering how that works.

The next blog post I will write will be on the Set Comprehension.

1 thought on “Python List Comprehensions”

  1. Pingback: Set Comprehension in Python | @terrameijar

Comments are closed.