With the following code, we can see that the modify operation in the last line fails – Python throws an error
TypeError: 'tuple' object does not support item assignment
However, if we look at the line below and print
a, we see that it did indeed do the operation of
Why is this? Shouldn’t the variable
a not be mutated if the REPL gives an error?
[nhouk@computer:~] $ python3 Python 3.5.3 (default, Nov 4 2021, 15:29:10) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = ([2, 3], "a", "b") >>> a +=  Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> a ([2, 3, 1], 'a', 'b')
The tuple is not mutated. The list contained in the tuple is.
a +=  is (roughly)
a = a +  (with the small nuance that it does not create a new list, so it is better compared to
a.append(1)). The right side successfully executes and appends
1 to the list, then the error is raised when you try to assign back to the tuple (
a = ...).
To achieve the same result without getting the error, use