Worth of [] +=

Alex Martelli aleaxit at yahoo.com
Fri Sep 15 00:05:56 CEST 2000


"Steve Juranich" <sjuranic at condor.ee.washington.edu> wrote in message
news:Pine.SOL.3.96.1000914105701.2501B-100000 at condor.ee.washington.edu...
> First off, I've only been hacking Python for about 2 months now, so please
> be patient.
>
> I'm a little confused about this whole thing of += with a list object.
> Didn't we already have that with the list.append() function?  Does the +=
> operate differently (so that end users like me will notice)?  If it does
> work differently, what will be the benefit of += that list.append() didn't
> have?

Polymorphism.  Say you have two sequences A and B: you don't know
if they're tuples or lists -- you only want to get a sequence with the two
concatenated (and don't care what happens to them afterwards, the
normal case).  If you knew they are tuples, you'd know you must do:
    A = A + B
as there is no alternative.  If you knew they are lists, you'd know that:
    A.extend(B)
may be more efficient -- rebinding A to A + B will work, but not as fast.

    A += B

takes care of both cases -- "does the right thing" automatically in
this common case.  If A is mutable, it gets mutated.  Else, a new
object is made, and A is re-bound to that.


So, you can now more easily write functions that will operate
well on either lists or tuples (or other kinds of sequences yet).
Your code is more reusable, more flexible, more general.


Of course, you do have to watch out for special cases in which
you do NOT want to mutate the object A is currently bound to
(because you have, or may have, other references to it in other
places, and must ensure they keep referring to an unchanged
list).  In this case, you must still to A = A + B (not extend nor
an append loop!).  But, more often, you need not take such
precautions.


Alex






More information about the Python-list mailing list