## List Comprehension

### Introduction

We learned in the previous chapter "Lambda Operator, Filter, Reduce and Map" that Guido van Rossum prefers list comprehensions to constructs using map, filter, reduce and lambda. In this chapter we will cover the essentials about list comprehensions.

List comprehensions were added with Python 2.0. Essentially, it is Python's way of implementing a well-known notation for sets as used by mathematicians. In mathematics the square numbers of the natural numbers are, for example, created by { x2 | x ∈ ℕ } or the set of complex integers { (x,y) | x ∈ ℤ ∧ y ∈ ℤ }.

List comprehension is an elegant way to define and create lists in Python. These lists have often the qualities of sets, but are not necessarily sets.

List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). For most people the syntax of list comprehension is easier to be grasped.

### Examples

In the chapter on lambda and map() we designed a map() function to convert Celsius values into Fahrenheit and vice versa. It looks like this with list comprehension:

```
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
print(Fahrenheit)
```

A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and the best known example is (3, 4, 5). The following list comprehension creates the Pythagorean triples:

```
[(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
```

Another example: Let A and B be two sets, the cross product (or Cartesian product) of A and B, written A×B, is the set of all pairs wherein the first element is a member of the set A and the second element is a member of the set B.

Mathematical definition: A×B = {(a, b) : a belongs to A, b belongs to B}. It's easy to be accomplished in Python:

```
colours = [ "red", "green", "yellow", "blue" ]
things = [ "house", "car", "tree" ]
coloured_things = [ (x,y) for x in colours for y in things ]
print(coloured_things)
```

### Generator Comprehension

Generator comprehensions were introduced with Python 2.6. They are simply like a list comprehension but with parentheses - round brackets - instead of (square) brackets around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list.

```
x = (x **2 for x in range(20))
print(x)
x = list(x)
print(x)
```

```
noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
primes = [x for x in range(2, 100) if x not in noprimes]
print(primes)
```

We want to bring the previous example into more general form, so that we can calculate the list of prime numbers up to an arbitrary number n:

```
from math import sqrt
n = 100
sqrt_n = int(sqrt(n))
no_primes = [j for i in range(2, sqrt_n+1) for j in range(i*2, n, i)]
no_primes
```

If we have a look at the content of no_primes, we can see that we have a problem. There are lots of double entries contained in this list:

```
```

The solution to this unbearable problem is easier than you may think. It's just a matter of changing square brackets into braces, or in other words: We will use set comprehension.

### Set Comprehension

A set comprehension is similar to a list comprehension, but returns a set and not a list. Syntactically, we use curly brackets instead of square brackets to create a set. Set comprehension is the right functionality to solve our problem from the previous subsection. We are able to create the set of non primes without doublets:

```
from math import sqrt
n = 100
sqrt_n = int(sqrt(n))
no_primes = {j for i in range(2, sqrt_n+1) for j in range(i*2, n, i)}
no_primes
```

```
primes = {i for i in range(2, n) if i not in no_primes}
print(primes)
```

```
from math import sqrt
def primes(n):
if n == 0:
return []
elif n == 1:
return []
else:
p = primes(int(sqrt(n)))
no_p = {j for i in p for j in range(i*2, n+1, i)}
p = {x for x in range(2, n + 1) if x not in no_p}
return p
for i in range(1,50):
print(i, primes(i))
```

x = "This value will be changed in the list comprehension" res = [x for x in range(3)] res [0, 1, 2] x 2 res = [i for i in range(5)] i 4

Guido van Rossum referred to this effect as "one of Python's 'dirty little secrets' for years".1 The reason for doing this was efficiency. "It started out as an intentional compromise to make list comprehensions blindingly fast, and while it was not a common pitfall for beginners, it definitely stung people occasionally."2

This "dirty little secret" is fixed in Python3, as you can see in the following code:

```
x = "Python 3 fixed the dirty little secret"
res = [x for x in range(3)]
print(res)
[0, 1, 2]
x
```

Footnotes: 1 Guido van Rossum: From List Comprehensions to Generator Expressions

2 dto.