0

As we know tuple is immutable. But at the same time it can contain mutable entities.

Say we have a next tuple:

x = (1, [1, 2])

Let's try to change first element:

x[0] = 10
----> 1 x[0] = 10
TypeError: 'tuple' object does not support item assignment

Yep. It is no wonder. Absolutely expected behavior.

Let's try to append an element to list in our tuple:

>>> x[1].append(3)    
(1, [1, 2, 3])

No any errors since we mutate a mutable entity as a list. There is the same reference to list.

And now let's try to append via +=:

 x[1] += [4]
----> 1 x[1] += [4]
TypeError: 'tuple' object does not support item assignment

>>> x
>>> Out[49]: (1, [1, 2, 3, 4])

Although there is TypeError value of our list have changed. I am a little bit confused.

What is the reason for such duality behavior?

xiº
  • 4,605
  • 3
  • 28
  • 39

0 Answers0