ProgrammingModerateProduct-company MCQ pattern

What is printed?

What is printed?
class Bag:
    items = []
    def add(self, v):
        self.items.append(v)

a, b = Bag(), Bag()
a.add(1); b.add(2)
print(a.items, Bag.items is b.items)
  1. A. [1] True
  2. B. [1, 2] True
  3. C. [1] False
  4. D. [1, 2] False

Correct answer: B. [1, 2] True

items is a CLASS attribute, so it is a single list shared by every instance. self.items.append changes it in place (there is no assignment, so no instance attribute is created). Both adds go into the same list.

More Python Programming questions

Exams that ask this topic