Tuples and immutability

John O'Hagan 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[1] += [20]
> > 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
> already.
> 
> 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[1].append(20)
>    >>> a_tuple[1].extend([20])
> 
> Try also:
> 
>    >>> a_tuple[1] = a_tuple[1]
> 

[...]

Also try:

x = a_tuple[1] #What's in a name?
x is a_tuple[1] #Obviously, but:
x += [1] #No error
a_tuple[1] += [1] #Error

Same object, just a different name - but a different result. I get why,
but still find that odd.

--

John







More information about the Python-list mailing list