Junior — Middle
Is it possible to modify the contents of a collection declared as a tuple?
sobes.tech AI
Answer from AI
Tuples in Python are immutable objects, meaning their contents cannot be changed after creation. However, if a tuple contains mutable objects, such as lists, the contents of these nested objects can be modified.
Example:
t = (1, 2, [3, 4])
t[2].append(5) # This is allowed
print(t) # (1, 2, [3, 4, 5])
# But attempting to change the tuple itself will raise an error:
t[0] = 10 # TypeError: 'tuple' object does not support item assignment
Thus, the tuple itself cannot be changed, but the contents of mutable elements inside it can be.