Unexpected result for list operator "+="

Fredrik Lundh fredrik at effbot.org
Thu Jan 4 03:37:26 EST 2001


Joe Smith wrote:
> I guess that list assignment is an assignment of the reference
> to the object and it does not copy the object.  Where as a string
> object gets copied (see example 2).

"plain assignment" (=) is always done by reference.

(See http://effbot.org/guides/python-objects.htm for
more info)

Augmented assignment operations (+= etc) are handled
by the object itself.  Some types are modified in place,
others return new objects.

Quoting 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."

    http://www.python.org/doc/ref/augassign.html

For list objects, "+=" is the same thing as calling the
"extend" method [1].

Hope this helps!

Cheers /F

1) if anyone can figure out where list += is documented,
let us know...





More information about the Python-list mailing list