Augument assignment versus regular assignment

Fredrik Lundh fredrik at pythonware.com
Sun Jul 9 05:00:36 EDT 2006


Frank Millman wrote:

> So it looks as if x +=  [] modifies the list in place, while x = x + []
> creates a new list.

objects can override the += operator (by defining the __iadd__ method), 
and the list type maps __iadd__ to extend.  other containers may treat 
+= differently, but in-place behaviour is recommended by the language
reference:

   An augmented assignment expression like x += 1 can be rewritten as
   x = x + 1 to achieve a similar, but not exactly equal effect.  In
   the augmented version, x is only evaluated once. Also, when possible,
   the actual operation is performed in-place, meaning that rather than
   creating a new object and assigning that to the target, the old object
   is modified instead.

</F>




More information about the Python-list mailing list