Computer Science · Ch 10 — Tuples and Dictionaries
Tuple is Immutable
Tuple is Immutable
A tuple is an immutable data type. Immutability means that once a tuple has been created, its elements cannot be changed. Any attempt to assign a new value to a position inside an existing tuple raises an error:
>>> t = (1, 2, 3, 4, 5)
>>> t[4] = 10
TypeError: 'tuple' object does not support item assignment
The TypeError message says it directly — a tuple does not support item assignment.
The subtle exception: a mutable element inside a tuple
Although the tuple itself cannot be changed, an element of a tuple may itself be of a mutable type, for example a list. In that case the contents of that list can still be modified — and the modification is visible when you display the tuple:
# the 4th element of this tuple is a list
>>> t = (1, 2, 3, [8, 9])
# modify an item INSIDE the list element
>>> t[3][1] = 10
# the change is reflected in the tuple
>>> t
(1, 2, 3, [8, 10])
Note carefully what happened: we never replaced the tuple's element (the list object is still the same element sitting at index 3); we only changed data inside that list. That is why no error occurs.