Junior — Middle
What happens if a mutable list is placed inside an immutable data structure like a tuple?
sobes.tech AI
Answer from AI
In Python, tuples are immutable data structures, meaning their contents cannot be changed after creation. However, if a mutable object, such as a list, is inside a tuple, the list itself can be modified — elements can be added, removed, or changed.
Example:
my_tuple = (1, 2, [3, 4])
my_tuple[2].append(5)
print(my_tuple) # Outputs: (1, 2, [3, 4, 5])
Thus, the immutability of a tuple only applies to the references to objects inside it, not the objects themselves. If a mutable object is inside a tuple, its contents can be changed, which may lead to unexpected behavior if this is not taken into account.