Python throws error, but still mutates tuple – is this a Python REPL bug?

Advertisements

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 += [1].

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[0] += [1]
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')

>Solution :

The tuple is not mutated. The list contained in the tuple is.

a[0] += [1] is (roughly) a[0] = a[0] + [1] (with the small nuance that it does not create a new list, so it is better compared to a[0].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[0] = ...).

To achieve the same result without getting the error, use append directly:

a[0].append(1)

Leave a ReplyCancel reply