Junior — Middle
Is it possible to modify a list that is an element of a tuple in Python?
sobes.tech AI
Answer from AI
In Python, a tuple is an immutable data type, meaning its structure cannot be changed (elements cannot be added, removed, or replaced). However, if an element of a tuple is a mutable object, such as a list, its contents can be modified.
Example:
my_tuple = (1, [2, 3], 4)
# You cannot do:
# my_tuple[1] = [5, 6] # Error, tuple is immutable
# But you can modify the list inside the tuple:
my_tuple[1].append(5)
print(my_tuple) # (1, [2, 3, 5], 4)
Thus, the tuple itself cannot be modified, but if it contains mutable objects, their internal state can be changed.