ProgrammingModerateTCS NQT · Wipro pattern

What is printed?

What is printed?
class Bag:
    items = []
    def add(self, x):
        self.items.append(x)
a, b = Bag(), Bag()
a.add(1)
b.add(2)
print(a.items, Bag.items, a.items is b.items)
  1. A. [2] [1] False
  2. B. [1, 2] [] False
  3. C. [1] [] False
  4. D. [1, 2] [1, 2] True

Correct answer: D. [1, 2] [1, 2] True

items is a class attribute, so every instance's self.items resolves to the same list object, which add changes in place.

More Python Programming questions

Exams that ask this topic