Unexpected result for list operator "+="

Alex Martelli aleaxit at yahoo.com
Thu Jan 4 03:55:18 EST 2001


"Joe Smith" <JoeSmith at bogusaddress.com> wrote in message
news:3A542778.E1BC06E3 at bogusaddress.com...
>
> I unexpectedly get l1 modified by doing "l += l2" (see example 1).  I take
> it is because l and l1 point to the same object.  If I use the string type
> instead of the list type, I don't get l2 modified.  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).

No, _everything_ goes by reference: but certain objects, such as strings,
are *immutable* -- others, such as lists, are *mutable*.  This is the
very reason for existence of _tuples_: they're just like lists, *except*
they are immutable (this allows them, for example, to be keys in a
dictionary: lists, being mutable, cannot be used as dictionary keys).

"Assigning-operators" such as += operate *in-place* (for speed) if this
is feasible (the left-hand operand is mutable), but, of course, not for
an immutable left-hand side -- in which case, a new object must be
created instead, and the left-hand side variable rebound to it.


So, given a sequence S, and another sequence X, the statement:

    S += X

operates differently for mutable or immutable S.  If S is mutable (list),
it works the same as
    S.extend(X)
i.e, just the same as
    S[-1:] = list(X)


If S is immutable, though, the statement becomes a rebinding,
exactly equivalent to
    S = S + X

You may use this form directly if you don't care about speed and
want to make sure S is re-bound to a totally new object, rather
than the already-existing object being modified.  There is, of
course, no way to ensure the existing object is modified: if it's
immutable, then it will NEVER be modified:-).


Alex






More information about the Python-list mailing list