Data Structures & AlgorithmsModerateTCS NQT Digital · Python semantics

Problem: What does the following print?

Problem: What does the following print?
a = [1, 2, 3]
b = a
b += [4]
print(a)
  1. A. [1, 2, 3]
  2. B. [4]
  3. C. [1, 2, 3, 4]
  4. D. Error

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

The += operator on a list extends it in place, so a and b remain the same object and a sees the new element.

More Coding Interview Problems questions

Exams that ask this topic