|
Original |
Translation |
|
49
|
[ expression for expr in sequence1 for expr2 in sequence2 ... for exprN in sequenceN if condition ]
|
|
|
50
|
The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are *not* iterated over in parallel, but from left to right; this is explained more clearly in the following paragraphs. The elements of the generated list will be the successive values of *expression*. The final :keyword:`if` clause is optional; if present, *expression* is only evaluated and added to the result if *condition* is true.
|
|
|
51
|
To make the semantics very clear, a list comprehension is equivalent to the following Python code::
|
|
|
52
|
for expr1 in sequence1: for expr2 in sequence2: ... for exprN in sequenceN: if (condition): # Append the value of # the expression to the # resulting list.
|
|
|
53
|
|
54
|
seq1 = 'abc' seq2 = (1,2,3) >>> [ (x,y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
|
|
|
55
|
To avoid introducing an ambiguity into Python's grammar, if *expression* is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct::
|
|
|
56
|
# Syntax error [ x,y for x in seq1 for y in seq2] # Correct [ (x,y) for x in seq1 for y in seq2]
|
|
|
57
|
The idea of list comprehensions originally comes from the functional programming language Haskell (http://www.haskell.org). Greg Ewing argued most effectively for adding them to Python and wrote the initial list comprehension patch, which was then discussed for a seemingly endless time on the python-dev mailing list and kept up-to-date by Skip Montanaro.
|
|
|
58
|
|
|