ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
x = [1, 2, 3]
y = [x, x]
y[0] = y[0] + [4]
y[1] += [5]
print(x, y)
  1. A. [1, 2, 3, 4, 5] [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
  2. B. [1, 2, 3, 5] [[1, 2, 3, 4], [1, 2, 3, 5]]
  3. C. [1, 2, 3] [[1, 2, 3, 4], [1, 2, 3, 5]]
  4. D. [1, 2, 3, 5] [[1, 2, 3, 4, 5], [1, 2, 3, 5]]

Correct answer: B. [1, 2, 3, 5] [[1, 2, 3, 4], [1, 2, 3, 5]]

y[0] + [4] makes a new list and stores it in slot 0, detaching that slot from x. y[1] += [5] extends the object in slot 1, which is still x itself.

More Python Programming questions

Exams that ask this topic