|
Original |
Translation |
|
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
|
|
|
|
59
|
|
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.
|
|
|
61
|
class Number: def __init__(self, value): self.value = value def __iadd__(self, increment): return Number( self.value + increment) n = Number(5) n += 3 print n.value
|
|
|
62
|
The :meth:`__iadd__` special method is called with the value of the increment, and should return a new instance with an appropriately modified value; this return value is bound as the new value of the variable on the left-hand side.
|
|
|
63
|
Augmented assignment operators were first introduced in the C programming language, and most C-derived languages, such as :program:`awk`, C++, Java, Perl, and PHP also support them. The augmented assignment patch was implemented by Thomas Wouters.
|
|