Inspired by reading footnote 4 of this article.
Consider the following scenario:
>>> t = (1,2, [3, 4])
>>> t[2] += [5,6]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
t[2] += [5,6]
TypeError: 'tuple' object does not support item assignment
Tuples are immutable. So, as expected, trying to add to the list inside the tuple raises an error.
However if we inspect our tuple, the list has been added to!! (I can imagine this leading to very hard to track down bugs)
>>> t
(1, 2, [3, 4, 5, 6])
Also, both extending
>>> t[2].extend([7,8])
>>> t
(1, 2, [3, 4, 5, 6, 7, 8])
and appending
>>> t[2].append(9)
>>> t
(1, 2, [3, 4, 5, 6, 7, 8, 9])
work without raising an error.
So, my questions are:
- If tuples are immutable, why is it possible to change a list within a tuple?
- Why does the first example raise an error and the other two not?
- In the first example, why is the list inside the tuple changed even though an error is raised?