ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Box:
    def __init__(self, items=[]):
        self.items = items

b1 = Box()
b2 = Box()
b1.items.append(1)
print(b2.items)
  1. A. []
  2. B. [1]
  3. C. AttributeError
  4. D. None

Correct answer: B. [1]

Both b1 and b2 receive the SAME default list object because it is created once when __init__ is defined. Appending through b1.items is visible through b2.items too.

More Python Programming questions

Exams that ask this topic