# List Comprehension（列表解析）

## 一、简介

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 list in Python. These lists have often the qualities of sets, but are not in all cases 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.

## 二、举例

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

The following list comprehension creates the Pythagorean triples:

Cross product of two sets:

## 三、生成器解析

Generator comprehensions were introduced with Python 2.6. They are simply a generator expression with a parenthesis - round 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.

## 四、一个更深入的例子

Calculation of the prime numbers between 1 and 100 using the sieve of Eratosthenes:

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:

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 intolerable problem comes with the set comprehension, which we will cover in the next section.

## 五、集合解析

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:

## 六、递归函数计算素数

The following Python script uses a recursive function to calculate the prime numbers. It incorporates the fact that it is enough to examine the multiples of the prime numbers up to the square root of n: