|
Original |
Translation |
|
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
|
This means that when there are multiple :keyword:`for`...\ :keyword:`in` clauses, the resulting list will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long::
|
|
|
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
|
|
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
|
|
|
|
59
|
Augmented assignment operators, another long-requested feature, have been added to Python 2.0. Augmented assignment operators include ``+=``, ``-=``, ``*=``, and so forth. For example, the statement ``a += 2`` increments the value of the variable ``a`` by 2, equivalent to the slightly lengthier ``a = a + 2``.
|
|
|
60
|
The full list of supported assignment operators is ``+=``, ``-=``, ``*=``, ``/=``, ``%=``, ``**=``, ``&=``, ``|=``, ``^=``, ``>>=``, and ``<<=``. Python classes can override the augmented assignment operators by defining methods named :meth:`__iadd__`, :meth:`__isub__`, etc. For example, the following :class:`Number` class stores a number and supports using += to create a new instance with an incremented value.
|
|