ProgrammingVery hardTCS NQT · Infosys HackWithInfy · Product Company SDE

What does the following Python 3 code print? a = [1, 2, 3] b = a[:] b.append(4) print(a, b)

  1. A. [1, 2, 3] [1, 2, 3, 4]
  2. B. [1, 2, 3, 4] [1, 2, 3, 4]
  3. C. [1, 2, 3, 4] [1, 2, 3]
  4. D. [1, 2, 3] [1, 2, 3]

Correct answer: A. [1, 2, 3] [1, 2, 3, 4]

a[:] makes a shallow copy with a new outer list, so appending to b leaves the original a untouched.

More Python Programming questions

Exams that ask this topic