$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · medium · #165

Which fix removes the bug?

handlers = []
for i in range(3):
    handlers.append(lambda: print(i))
for h in handlers:
    h()
  1. Bind i as a default arg
  2. Use a list comprehension
  3. Call the lambda at once
  4. Declare i as nonlocal
The closures share one i, so all three print 2; lambda i=i: captures per iteration.
Play Problem Solving ▸