4

If I have a list inside a tuple, and then attempt to concatenate that list with another, I get an exception:

>>> a = ([1], [2])
>>> a[1] += [3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

This is expected: the concatenation is creating a new list, and tuples are immutable. However, despite the exception, the tuple is updated:

>>> print(a)
([1], [2, 3])

Why is this the case?

lumisota
  • 101
  • 4

1 Answers1

5

That's because the concatenation (+) happens first, and then the assignment.

As the elements of the tuple here are lists which are mutable, the a[1] + [3] would succeed, but as the tuple itself is immutable, the assignment of the output of the concatenation to a[1] would fail (expectedly).

heemayl
  • 39,294
  • 7
  • 70
  • 76