ProgrammingHardTCS NQT · Infosys

What is the output of this Python code? t = ([1], 5) try: t[0] += [2] except TypeError: print("err", end=" ") print(t)

  1. A. err ([1], 5)
  2. B. ([1, 2], 5)
  3. C. err ([1, 2], 5)
  4. D. ([1], 5)

Correct answer: C. err ([1, 2], 5)

t[0] += [2] first extends the list in place (list.__iadd__), then tries to assign the result back into the tuple, which raises TypeError. The exception is caught, but the list was already mutated, so t is ([1, 2], 5).

More Python Programming questions

Exams that ask this topic