Lambda Function
A lambda is an anonymous function defined with the lambda keyword rather than def. Syntax: lambda parameters: expression. The expression is evaluated and r...
What is a Lambda?
A lambda is an anonymous function defined with the lambda keyword rather than def. Syntax: lambda parameters: expression. The expression is evaluated and returned automatically; there is no explicit return statement. Example: square = lambda x: x**2; square(5) gives 25. Lambdas are limited to a single expression — no statements (like if-else blocks in statement form, loops, or assignments). They are intended for short, one-off functions used inline.
Lambda with Multiple Parameters
A lambda can take multiple parameters separated by commas: add = lambda a, b: a + b; add(3, 4) gives 7. It can also take no parameters: hello = lambda: "Hello, World!". Lambdas support default arguments (lambda x, y=1: x * y) and *args (**kwargs are supported but rare). The conditional expression (ternary) is allowed inside a lambda body: clamp = lambda x, lo, hi: lo if x < lo else hi if x > hi else x.
Lambda in sorted and map
Lambdas are most commonly used as the key argument to sorted() and as the function argument to map() and filter(). Example sorting a list of tuples by the second element: data = [(1, "b"), (2, "a"), (3, "c")]; data.sort(key=lambda t: t[1]) sorts alphabetically by the string. This avoids defining a named function for something used only once. sorted(students, key=lambda s: s.gpa, reverse=True) sorts students by GPA descending.
When NOT to Use Lambda
PEP 8 discourages assigning a lambda to a variable: square = lambda x: x**2 is worse than def square(x): return x**2. The def form provides a meaningful __name__ attribute for debugging, is more readable, and can include a docstring. Reserve lambdas for cases where you truly need a short, unnamed function in-place — like as an argument to sorted, map, or filter. Using lambdas for complex logic is an antipattern that harms readability.
Closures with Lambda
Lambdas capture variables from their enclosing scope, just like regular inner functions. A classic gotcha: funcs = [lambda: i for i in range(3)]. All three lambdas capture the same i variable, so calling any of them after the loop gives 2 (the final value of i). The fix: use a default argument to bind the current value: funcs = [lambda i=i: i for i in range(3)]. Now each lambda has its own copy of i captured at the moment of creation.
Exam Tip
The lambda loop closure gotcha is a very common exam question. Given funcs = [lambda: x for x in [1,2,3]], what does funcs[0]() return? It returns 3 — the final value of x after the loop completes, not 1. All three lambdas share the same x variable from the enclosing scope. To fix this, pass x as a default argument. Another question: can a lambda contain a for loop or an assignment statement? No — only a single expression is allowed.