lambda — Advanced Examples
Creates a small anonymous (unnamed) function in a single expression
Lambda closures and pitfalls
Understanding how lambda captures variables.
python
# Pitfall: lambda captures by reference, not value funcs = [lambda: i for i in range(5)] print([f() for f in funcs]) # All return 4! # Fix: capture value with default argument funcs = [lambda i=i: i for i in range(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())
Lambda captures variables by reference, not by value. The default argument trick (lambda i=i: ...) forces capture at definition time.
Want to try these examples interactively?
Open Advanced Playground