0

A colleague just posted this Python execution:

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

Python complains that we cannot do a[0] += [5] since tuples are immutable, but it has done the assignment. What is going on and why has Python performed the command while simultaneously complaining that it cannot perform the command?

dumbledad
  • 16,305
  • 23
  • 120
  • 273
  • 1
    Python first appends to the `list` (which is allowed), then tries to assign 0th position of the `tuple` the new list, which is not allowed. mcoding explains this in detail in his video [Python's sharpest corner is ... plus equals? (+=)](https://www.youtube.com/watch?v=cGveIvwwSq4) – ertucode Jan 18 '23 at 06:30

0 Answers0