MiddleCodeOccasionalNot answered yet
What happens with t[0] += [100] on a tuple?
Predict what each line does.
t = ([1], 2)
t[0].append(99) # (1)
print(t)
t[0] += [100] # (2) what happens?
Determine the output and explain.
(1) succeeds → ([1, 99], 2): the tuple is immutable, but the list it references is mutable. (2) is the famous trap: += mutates the list AND tries to reassign t[0], so it raises TypeError — yet the list is still mutated to [1, 99, 100]. The operation half-succeeds.
- ✗Thinking tuple immutability protects the mutable objects it holds
- ✗Expecting line (2) to leave the list unchanged after the error
- ✗Believing the
TypeErrorrolls back the in-place mutation
- →Why does
+=both mutate the list and attempt an assignment tot[0]? - →What does this reveal about whether a tuple is truly 'immutable'?