Data Structures & AlgorithmsHardAmazon · Microsoft OA

Edge case: += versus + on a list that has another name.

Edge case: += versus + on a list that has another name.
a = [1, 2, 3]
b = a
a += [4]
a = a + [5]
print(b, a)
What is printed?
  1. A. [1, 2, 3, 4] [1, 2, 3, 4, 5]
  2. B. [1, 2, 3] [1, 2, 3, 4, 5]
  3. C. [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
  4. D. [1, 2, 3, 4] [1, 2, 3, 4]

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

a += [4] extends the list IN PLACE, so b (the same object) sees 4. a = a + [5] builds a NEW list and rebinds a, leaving b unchanged.

More Coding Interview Problems questions

Exams that ask this topic