Programming · Flashcard

What does t[0] = 9 do when t is the tuple (1, 2, 3)?

  • ARaises TypeError — a tuple cannot be modified in place
  • BRebinds t to (9, 2, 3) — the tuple is copied on write
  • CNothing at all — item assignment on a tuple is a no-op
  • DReplaces element 0 in place — tuples resize but stay ordered

Why this is the answer

Tuples are immutable, so they support no item assignment: the statement raises TypeError: 'tuple' object does not support item assignment. Python never silently swaps one object for another behind your back, the failure is loud rather than ignored, and no element is replaced. That immutability is also why a tuple can be a dict key while a list cannot.

Official docs
Study in Gnoseed →