Unexpected result for list operator "+="

Moshe Zadka moshez at zadka.site.co.il
Thu Jan 4 05:40:07 EST 2001


On Thu, 4 Jan 2001, "Alex Martelli" <aleaxit at yahoo.com> wrote:

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

Let me rephrase what Alex said in different terms: += and its ilk are
so-called linear update operations. That is to say, do them *only*
if you know you have not created aliases for your objects.

Good example:

l=[1,2,3]
l += [4]

Bad example:

l=[1,2,3]
old_l = l
#     ^ create an alias to l, called "old_l"
l += [4]

If you follow this advice, then simply treat the in-place semantics
as "always creates a new object -- but has nifty optimizations sometimes".





More information about the Python-list mailing list