1

I encountered to this example about python mutable and immutable:

t = (1, 2, [3, 4])
t[2] += [5, 6]

This will raise error:

TypeError: 'tuple' object does not support item assignment

Until here I can understand the error because t is a tuple and tuples are immutable, but problem is t changed.

print(t)
# Output (1, 2, [3, 4, 5, 6])

an other thing is attempt to change t[2] by using append or extend has no error and works fine.

t[2].extend([7,8])
t[2].append(9)
print(t)
# Output (1, 2, [3, 4, 5, 6, 7, 8, 9])

Can anyone explain this?

mastisa
  • 1,875
  • 3
  • 21
  • 39
  • You can check this on the docs: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences – GeeTransit Jun 12 '19 at 11:30
  • 1
    Although `t[2] += [5,6]` does alter the list in place, it *also* tries to write the result back to `t[2]`, as if you wrote `t[2] = t[2] + [5,6]`. That means trying to alter `t`, which is immutable. – khelwood Jun 12 '19 at 11:30
  • @Chris_Rands You might say that, but in fact `+=` on a list _does_ modify the list in place. – khelwood Jun 12 '19 at 11:34
  • @khelwood yes, sorry you're correct – Chris_Rands Jun 12 '19 at 11:37
  • 3
    I think that [this question](https://stackoverflow.com/questions/9172263/a-mutable-type-inside-an-immutable-container) would be a better duplicate, as it explains why the `+=` syntax raises an error while the `.extend()` doesn't, though [the documentation](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) describes them as equivalent. – Thierry Lathuille Jun 12 '19 at 11:46
  • @ThierryLathuille Good find. – khelwood Jun 12 '19 at 12:51

0 Answers0