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