Python Lambda
Python · Functions & OOP
Theory
A lambda is a small anonymous function written in a single expression: lambda arguments: expression. It has no name and no return keyword - the value of the expression is returned automatically. lambda x: x * x is the same as def square(x): return x * x, just shorter.
Lambdas shine when another function needs a short function as input. sorted(rows, key=lambda r: r[1]) sorts a list of (name, salary) tuples by salary; filter(lambda s: s > 100, sales) keeps only large sales; map(lambda s: s * 1.18, prices) adds 18% GST to every price. Because a lambda can hold only one expression, it cannot contain statements like if-blocks, loops or assignments (a conditional expression a if cond else b is allowed).
Why we use it
Many built-ins (sorted, min, max, map, filter) and pandas methods (apply) take a function as an argument. A lambda lets you write that throwaway function right where it is used instead of defining a named function elsewhere.
When to use it
Use a lambda for short, single-expression logic passed to another function, such as a sort key. If the logic needs several lines, a docstring or reuse in many places, write a normal def function instead.
How it works
- sorted(rows, key=lambda r: r[1])
- sorted() takes each tuple from rows
- Call the lambda on it to get the key r[1] (salary)
- Compare items by their keys
- Are all items placed in order? Yes: Return the new sorted list. No: Keep comparing keys.
- Result: rows ordered by salary
Syntax
lambda arguments: expressionExample
square = lambda x: x * x
square(5) # 25Key points
- Commonly used with map(), filter(), sorted(), min(), max()
- Limited to a single expression, no statements
- The expression's value is returned automatically - no return keyword
- Assigning a lambda to a name works, but a def is clearer for named functions
- In pandas, df['col'].apply(lambda x: ...) runs it on every value