Tuple Immutability and Mutable Members
Core idea
A tuple fixes the references stored in its positions. You cannot replace or delete a position in an existing tuple. However, an item may refer to a mutable object, such as a list, and that object can still change. Rebinding the name of a tuple is also allowed.
Tuple item assignment is not supported.
Modify a contained list
record = ("A", [2, 5])record[1].append(8)print(record)The second slot still references the same list, whose contents changed.
Build a replacement tuple
point = (4, 7)old = pointpoint = (9, point[1])print(old, point)Rebinding point does not change the earlier tuple.
Common mistake
An immutable container does not make everything inside it immutable. Do not treat tuples containing lists as deeply frozen data.
Practice
Create a tuple containing an empty list. Append a value to the list and explain why this succeeds while assigning to the tuple index does not.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tuple immutability
Check your understanding of tuple immutability.
Which error occurs?
pair = (1, 2)pair[0] = 7What is printed?
pair = (1, [2])pair[1].append(3)print(pair)What is printed?
a = (1, 2)b = aa = (9, 2)print(b)What does tuple immutability guarantee?