Question discussion

What is the output of the following Python code?t = ([1, 2], 3) try: t[0] += [4] except TypeError: pass print(t, len(t[0]))

1911Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Python code?

t = ([1, 2], 3)
try:
    t[0] += [4]
except TypeError:
    pass
print(t, len(t[0]))
  • A([1, 2, 4], 3) 3
  • B([1, 2], 3) 2
  • C([1, 2, 4], 3) 2
  • DThe code ends with an unhandled TypeError
Correct answer: A

Explanation

The in-place list extension succeeds first, and only the following assignment to the tuple slot raises the (caught) TypeError, so the inner list has still changed.

Discussion 0

Nobody has replied yet. Start the discussion!