Next / Previous / Contents / TCC Help System / NM Tech homepage

11.2. List comprehensions

You can use a form called a list comprehension to create a list. The general form is:

[ e
  for v1 in s1
  for v2 in s2
  ...
  if c ]

where e is some expression, followed by one or more for clauses, optionally followed by an if clause.

The result is a list containing all the values of expression e after all the nested for loops have been run; the for loops have the same structure as in Section 23.4, “The for statement: Iteration over a sequence”. If there is an “if” clause, it determines which values of e are added to the list: if the if condition is true, the value is added, otherwise it is not added.

This is perhaps easiest to explain with a few examples. In the first example, we construct a list containing the cubes of the numbers from 1 to 10, inclusive. The for loop generates the numbers 1, 2, ..., 10, and then the expression “x**3” cubes each one and appends it to the resulting list.

>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [ x**3 for x in range(1,11 ) ]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

In the next example, we use two for loops. The outer loop generates the sequence [1, 2, 3], and the inner loop generates the sequence [50, 51]. The expression “x*1000 + y” is computed for each of the resulting six value sets for x and y, and the result is appended to the list being built.

>>> [ x*1000 + y
...   for x in range(1,4)
...   for y in range(50, 52) ]
[1050, 1051, 2050, 2051, 3050, 3051]

In the next example, there are two nested loops, each generating the sequence [0, 1, 2]. For each of the nine trips through the inner loop, we test the values of x and y and discard the cases where they are equal. The expression “(y, x)” combines the two values into a 2-tuple.

>>> [ (y, x)
...   for y in range(3)
...   for x in range(3)
...   if x != y ]
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]