Tuples and immutability
research at johnohagan.com
Fri Feb 28 06:17:10 CET 2014
On Thu, 27 Feb 2014 18:19:09 +0200
Marko Rauhamaa <marko at pacujo.net> wrote:
> Eric Jacoboni <eric.jacoboni at gmail.com>:
> >>>> a_tuple += 
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in <module>
> > TypeError: 'tuple' object does not support item assignment
> > [...]
> > But, then, why a_tuple is still modified?
> That's because the += operator
> 1. modifies the list object in place
> 2. tries to replace the tuple slot with the list (even though the
> list hasn't changed)
> It's Step 2 that raises the exception, but the damage has been done
> One may ask why the += operator modifies the list instead of creating
> a new object. That's just how it is with lists.
> BTW, try:
> >>> a_tuple.append(20)
> >>> a_tuple.extend()
> Try also:
> >>> a_tuple = a_tuple
x = a_tuple #What's in a name?
x is a_tuple #Obviously, but:
x +=  #No error
a_tuple +=  #Error
Same object, just a different name - but a different result. I get why,
but still find that odd.
More information about the Python-list