[Tutor] Standard way to append to a list? ['+=' is in-place concatenation]

Magnus Lyckå magnus@thinkware.se
Thu Apr 17 17:09:01 2003


At 17:59 2003-04-16 -0700, Danny Yoo wrote:
>Clarification on the second form: the expression:
>
>     l += [4]
>
>is called an 'in-place concatenation', and for lists, this actually calls
>the extend() method!  For those with a C bent, here's the relevant code
>from the Python source:

Hm... I didn't know that. The language reference calls += in general
"augmented assignment". See 
http://www.python.org/doc/current/ref/augassign.html

As you write, the important thing is: "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".

This is tricky, because seeing x += y as a shorter way of writing x = x + y
is then incorrect for lists, as can be seen here:

 >>> a = [1,2,4]
 >>> b = a
 >>> b += [2]
 >>> a
[1, 2, 4, 2]
 >>> b
[1, 2, 4, 2]

a and b are still the same object.

 >>> a = [1,2,4]
 >>> b = a
 >>> b = b + [2]
 >>> a
[1, 2, 4]
 >>> b
[1, 2, 4, 2]
 >>>

b = b + [2] means that b no longer refers to the same object as a.

As another example, this means that in a ZODB persistent class,
"self.prop = self.prop + [x]" will automatically be recognized by the
object database, but with "self.prop += [x]" it won't...

I could get hit by that... Thanks Danny.

BTW, does "when possible" mean anything except list in the standard library?
I don't think there is any mutable type except list which can use += in
Python. How Python classes behave is obviously depending on how you implement
__iadd__, right? The code below is legal python, if not very good...

 >>> class x(list):
...     def __iadd__(self, other):
...             return "X"

So, I guess "when possible" is mainly a guideline for programmers...
E.g. in a Python class, you ought to modify self and end the method with
"return self".

/Magnus