ProgrammingModerateInfosys · Accenture · Capgemini pattern

What is printed?

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

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

b = a makes b another name for the same list, and += on a list extends it in place. So the change made through b shows up when a is printed.

More Python Programming questions

Exams that ask this topic