Why can a tuple be changed indirectly even though tuples are immutable?
Quick answer
A tuple’s items cannot be reassigned, but an item can refer to a mutable object, such as a list. You can change that list without replacing the tuple item. For example, t = ([1, 2],) followed by t[0].append(3) changes the list’s contents, while the tuple still refers to that list. By contrast, t[0] = [4] attempts to replace the tuple item and is not allowed. [S1]
The question, the details, the next step.
A practical checklist
Identify the object held at the tuple position that appears to change.
Check whether the operation mutates that object or tries to assign a new tuple item.
Compare the contained object’s contents before and after the operation.
Remember that printing a tuple can show updated contents of a mutable object it contains.
A few more useful answers
Does `t[0].append(3)` replace the first tuple item?
No. It changes the list referred to by the first item; it does not assign a different item to that tuple position. [S1]
Why does printing the tuple show the new list contents?
The tuple still refers to the list, and the display shows the list’s current contents.
Can I assign a new list with `t[0] = [4]`?
No. That attempts to reassign a tuple item, which is not allowed. [S1]
Sources
References used for this guide.
- [S1] Python Tutorial: Tuples and sequences docs.python.org · Checked
