I had read that Python tuples cannot be modified, after they are created. For example, item assignment is not allowed for tuple objects. However, if I have list objects inside a tuple, then I am allowed to append to that list. So, shouldn't Python disallow that, as we are basically modifying a tuple?
Asked
Active
Viewed 146 times
4
-
1My guess is that the tuple only holds a reference to the list. So you are allowed to modify what is referred to, but not the reference itself. – grc Oct 19 '14 at 02:08
-
2See a detailed answer here: https://stackoverflow.com/questions/9755990/why-can-tuples-contain-mutable-items – Totem Oct 19 '14 at 02:08
2 Answers
2
From python's documentation:
The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.
In some respect it means that the objects inside the tuple still have the same identity or id
:
>>> t
([0],)
>>> id(t[0])
140282665826440
>>> t[0].append(1)
>>> t
([0, 1],)
>>> id(t[0])
140282665826440 # same as in above

behzad.nouri
- 74,723
- 18
- 126
- 124
1
The immutability of a tuple is shallow: you cannot change what objects the tuple refers to. But if those objects are themselves mutable, you can mutate them.

Ned Batchelder
- 364,293
- 75
- 561
- 662