CS FundamentalsVery hardProduct-company placement · Python interview

This Observer code registers three listeners. What does it print?

This Observer code registers three listeners. What does it print?
class Subject:
    def __init__(self): self.obs = []
    def attach(self, f): self.obs.append(f)
    def notify(self, v):
        for f in self.obs: f(v)
log = []
s = Subject()
for k in range(3):
    s.attach(lambda v: log.append(v * k))
s.notify(10)
print(log)
  1. A. [0, 10, 20]
  2. B. [20]
  3. C. [20, 20, 20]
  4. D. [0, 0, 0]

Correct answer: C. [20, 20, 20]

All three lambdas close over the same variable k, looked up when they run; by then the loop has finished with k = 2, so each appends 10 x 2. Binding the value (lambda v, k=k: ...) would give [0, 10, 20].

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic