ProgrammingHardProduct-company MCQ pattern

What is printed?

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

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

a = a + [4] builds a NEW list and rebinds a, so b still refers to the old [1, 2, 3]. b += [5] then extends that old list in place. The two names end up with different lists.

More Python Programming questions

Exams that ask this topic