6

I am trying to understand the following error in python:

In []: tup = tuple(['foo', [1,2], True])
In []: tup[1]+=[2]

This leads to the following error:

TypeError: 'tuple' object does not support item assignment

I understand this is because tuples are not mutable. However, the second element of the tuple is now mutated in the manner I desired.

In []: tup
Out[]: ('foo', [1, 2, 2], True)

Can someone please explain what happened here. I got an error but the code did exactly what I wanted. What did the code fail to accomplish that is being shown by the error?

Also, I understand that the append method can accomplish the same.

In []: tup[1].append(2)
In []: tup
Out[]: ('foo', [1, 2, 2, 2], True)

But I still want to understand what happened in the first case above.

Bilal Khan
  • 63
  • 4
  • 3
    It's due to the `+=` operator. This operator is encouraged to modify its target in-place, but not required to do so. Because of this, it is always assumed that the target may in fact be a new object, so it assigns the result to it even if (as in the case of a list) it hasn't changed, but only its contents have changed. So in your case, it's doing (1) update the list then (2) assign the list to the tuple member (which is what fails). – Tom Karzes Jan 31 '18 at 14:35

0 Answers0