CS FundamentalsVery hardGATE CS · Software Engineering · Advanced

What is printed?

What is printed?
class S:
    def __init__(self): self.obs = []
    def notify(self, x):
        for o in self.obs:
            o(x)
log = []
def a(x):
    log.append(('a', x)); s.obs.remove(a)
def b(x):
    log.append(('b', x))
s = S()
s.obs += [a, b]
s.notify(1)
s.notify(2)
print(log)
  1. A. [('a', 1), ('b', 1), ('a', 2), ('b', 2)]
  2. B. [('a', 1), ('b', 2)]
  3. C. [('a', 1), ('b', 1), ('b', 2)]
  4. D. [('a', 1), ('a', 2), ('b', 2)]

Correct answer: B. [('a', 1), ('b', 2)]

Removing a from the list while the for loop iterates over it shifts b into the slot the iterator has already passed, so b is skipped in the first notification; in the second notification only b remains. A copy (list(self.obs)) would avoid the bug.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic