ProgrammingVery hardTCS NQT · Infosys · GATE CS

What does this Python code print? class A: items = [] n = 0 def add(self, x): self.items += [x] self.n += 1 a, b = A(), A() a.add(1); b.add(2); b.add(3) print(A.items, a.n, b.n, A.n)

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

Correct answer: B. [1, 2, 3] 1 2 0

self.items += [x] mutates the single shared class-level list in place (then rebinds the same object on the instance), so A.items holds all three values. self.n += 1 reads the class int but creates a new instance attribute, so A.n stays 0.

More Python Programming questions

Exams that ask this topic