Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading