Question discussion

What is the output of the following Python code?x = [1, 2, 3] y = x y += [4] z = x + [5] print(x, z)

1148Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Python code?

x = [1, 2, 3]
y = x
y += [4]
z = x + [5]
print(x, z)
  • A[1, 2, 3, 4] [1, 2, 3, 4, 5]
  • B[1, 2, 3, 4] [1, 2, 3, 5]
  • C[1, 2, 3] [1, 2, 3, 5]
  • D[1, 2, 3] [1, 2, 3, 4, 5]
Correct answer: A

Explanation

y += [4] extends the shared list in place so x becomes [1, 2, 3, 4]; x + [5] then creates a new list.

Discussion 0

Nobody has replied yet. Start the discussion!