# Pitfall: lambda captures by reference, not value
funcs = [lambda: i for i inrange(5)]
print([f() for f in funcs]) # All return 4!# Fix: capture value with default argument
funcs = [lambda i=i: i for i inrange(5)]
print([f() for f in funcs]) # Returns [0, 1, 2, 3, 4]# Lambda in callbacks
handlers = {}
for event in ["click", "hover", "scroll"]:
handlers[event] = lambda e=event: f"Handling {e}"for name, handler in handlers.items():
print(handler())
Output
Click "Run" to execute your code
Lambda captures variables by reference, not by value. The default argument trick (lambda i=i: ...) forces capture at definition time.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?