Python List Comprehensions Enhancement

Greg Ewing, September 1999

This enhancement extends the syntax of Python 1.5.2 to include what are known in some other languages as list comprehensions. Here are some examples:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
fruit = ["Apple", "Banana", "Pear"]
mult3 = [3 * x for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
crossprod = [(x, y) for x in numbers for y in fruits]


You can download the patch from:

What it provides

The syntax of a list constructor is extended as follows:
atom: '[' testlist [list_iter] ']'
list_iter: list_for | list_if
list_for: 'for' exprlist 'in' testlist
list_if: 'if' test
The semantics are such that the statement
x = [e for v1 in s1 for v2 in s2 ... if t ...]
is equivalent to
x = []
for v1 in s1:
  for v2 in s2:
      if t:

How it Works

The implementation is pretty straightforward. Code is generated almost exactly as if the above transformation had been carried out on the source. A temporary local variable is created (named so as not to conflict with any existing ones) to hold the list while it is being constructed; afterwards its value is loaded onto the stack and it is deleted.