append on lists

Hrvoje Niksic hniksic at xemacs.org
Tue Sep 16 08:22:19 EDT 2008


Armin <a at nospam.org> writes:

> What's the value of 1.add(b)?  None? Or 3 ??
> (if add works in the same way as append)

That's exactly the point -- __add__ doesn't work as append.  append is
a "destructive" operation, that mutates an existing object, whereas
__add__ returns a different object to be used as the "result" of the
addition.  This is why append doesn't need to return anything, while
__add__ must return the new object.

The distinction is even more apparent with sort and sorted, which are
destructive and non-destructive aspects of the same operation:

>>> a = [3, 2, 1]
>>> a.sort()         # destructive (mutates object), so no return value
>>> a
[1, 2, 3]

>>> a = [3, 2, 1]
>>> b = sorted(a)    # non-destructive (sorts a copy), returns the sorted copy
>>> a
[3, 2, 1]
>>> b
[1, 2, 3]



More information about the Python-list mailing list