Data Structures & AlgorithmsHardTCS NQT Digital · Infosys

Problem: What does this print? x = [1, 2, 3] y = x y += [4] z = x[:] z.append(5) print(len(x), len(z))

  1. A. 3 5
  2. B. 4 4
  3. C. 4 5
  4. D. 3 4

Correct answer: C. 4 5

y and x are the same list object, so += changes x; z is a shallow copy taken after that change, so it has one more element than x after append. Assuming y is a copy leaves x with three elements.

More Coding Interview Problems questions

Exams that ask this topic