Tuples and immutability

Marko Rauhamaa marko at pacujo.net
Thu Feb 27 11:19:09 EST 2014


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]


Marko



More information about the Python-list mailing list