Skip to content

✢ List Comprehension

Learning Objectives

At the end of this sub-unit, students should

  • understand list comprehension.

Mathematical Set Notation

In set theory of mathematics, we can construct a set from another set using the concept of predicates in a set-builder notation. A predicate is a symbol that represents a property or a relation. Without going into details of what it is mathematically1, we will simply note that the notation used \(P(x)\) means that the value \(x\) satisfies the predicate \(P\).

As a programmer, we will simply say that we can represent a predicate \(P(x)\) as a function P(x) that returns boolean value. If the return value is True, then x satisfies the predicate. Otherwise, if the return value is False, then x does not satisfy the predicate.

To use predicate in a set-builder notation, mathematicians use the following notation.

\[ \{F(x) \mid x \in S \land P(x) \} \]

Here, \(S\) is another set that we have construct before, \(P\) is the predicate from before, and \(F\) is a general function. In Python, we are not constructing a set. Instead, we construct a list. Assume that we have a list called S, a predicate P, and a function F, the set-builder notation above can be written as a list comprehension below.

[F(x) for x in S if P(x)]

Using this notation, we can simplify quite a number of set creation. Consider the initial list lst = [1, 2, 3, 4, 5]. We can construct the following sets easily.

Double the Value

dbl = [n * 2 for n in lst]
print(dbl)
[2, 4, 6, 8, 10]

Only Odd Number

odd = [n for n in lst if n % 2 == 1]
print(odd)
[1, 3, 5]

Square of the Even Number

sqr = [n * n for n in lst if n % 2 == 0]
print(sqr)
[4, 16]

  1. We are, after all, a programmer.