next up previous contents
Next: Functions Up: Programming Previous: Control in Loops: break   Contents


List Comprehensions

When you're using a for loop to process each element of a list, you can sometimes use a construction known as a list comprehension, which was instroduced into version 2.0 of python, to simplify the task. The basic format of a list comprehension is

[expression for var-1 in seq-1 if condition-1 for var-2 in seq-2 if condition-2 ...]
and the returned value is a list containing expression evaluated at each combination of var-1, var-2,$\ldots$ which meets the if conditions, if any are present. The second and subsequent for's, and all of the if's are optional. For example, suppose we wanted to create a list containing the squared values of the elements in some other list. We could use a for loop in the following way:
>>> oldlist = [7,9,3,4,1,12]
>>> newlist = []
>>> for i in oldlist:
...     newlist.append(i*i)
... 
>>> newlist
[49, 81, 9, 16, 1, 144]
Using a list comprehension, we can express this more succinctly:
>>> newlist = [i * i for i in oldlist]
By using if clauses within the list comprehension, we can be more selective about the elements we return:
>>> [i * i for i in oldlist if i % 2 == 1]
[49, 81, 9, 1]
When you have more than one for clause, all possible combinations of the variables in the for clauses will be evaluated:
>>> [(x,y) for x in range(3) for y in range(4)]
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), 
 (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
if clauses can be added after either of the for clauses; to refer to combinations involving all the variables, use an if clause at the very end:
>>> [(x,y) for x in range(3) if x in (1,2) for y in range(4) if y == 0]
[(1, 0), (2, 0)]
>>> [(x,y) for x in range(3) for y in range(4) if x + y < 3]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0)]

next up previous contents
Next: Functions Up: Programming Previous: Control in Loops: break   Contents
Phil Spector 2003-11-12