[Python-ideas] clear() method for lists

Oleg Broytman phd at phd.pp.ru
Thu Feb 11 16:35:23 CET 2010


On Thu, Feb 11, 2010 at 03:21:27PM +0000, Matthew Russell wrote:
> this seems to work in python 2.x and python3.1, although I suspect it's a
> bug.
> 
> >>> t = (1, 2)
> >>> t += (3,)
> >>> t
> (1, 2, 3)

   It's not a bug. += is not obliged to increase (extend) objects in place.
In case of read-only objects += creates a new extended object and returns
it:

>>> a = 2
>>> a += 1
>>> print a
3

   You don't suppose that 2 magically became 3, do you? Instead += replaces
an integer object pointed to by a with a different integer object.
   The same is true for tuples. The original tuple of len 2 was replaced by
a completely new tuple of len 3. If you hold a reference to the original
tuple you can find it's still intact:

>>> a = (1, 2)
>>> b = a # b *is not* a copy, b holds a reference *to the same tuple*
>>> a += (3,) # Now points to a different tuple
>>> a
(1, 2, 3)
>>> b # But the original tuple is still the same
(1, 2)

Oleg.
-- 
     Oleg Broytman            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.



More information about the Python-ideas mailing list