Python Lambda
A Python lambda is a small anonymous function written in a single expression. The syntax is lambda arguments: expression. Lambdas are most useful when a function needs another function as an argument, for example to tell sorted() how to compare items.
Lambda Syntax
A lambda can take any number of arguments, but its body must be one expression, whose value is returned automatically.
square = lambda x: x * x
add = lambda a, b: a + b
print(square(6))
print(add(3, 4))36 7
Assigning a lambda to a name like this works, but the style guide prefers a normal def for named functions. The real strength of lambdas is passing them straight into other functions.
Sort with a Lambda
The key argument of sorted(), sort(), min() and max() accepts a function that picks what to compare.
products = [("Olive Oil", 18.75), ("Green Tea", 6.0), ("Coffee", 22.0)]
by_price = sorted(products, key=lambda p: p[1])
print(by_price)
cheapest = min(products, key=lambda p: p[1])
print(cheapest[0])[('Green Tea', 6.0), ('Olive Oil', 18.75), ('Coffee', 22.0)]
Green TeaLambda with map() and filter()
map() applies a function to every item, and filter() keeps only the items for which the function returns True. Both return iterators, so wrap them in list() to see the result.
nums = [1, 2, 3, 4, 5, 6]
doubled = list(map(lambda n: n * 2, nums))
evens = list(filter(lambda n: n % 2 == 0, nums))
print(doubled)
print(evens)[2, 4, 6, 8, 10, 12] [2, 4, 6]
Many Python developers find list comprehensions such as [n * 2 for n in nums] clearer than map() and filter(). Both are correct; choose whichever reads better.
Lambdas that Create Functions
A function can return a lambda, producing customised functions on demand. The lambda remembers the value of rate from when it was created.
def make_discount(rate):
return lambda price: round(price * (1 - rate), 2)
ten_off = make_discount(0.10)
half_off = make_discount(0.50)
print(ten_off(80))
print(half_off(80))72.0 40.0
Lambda vs def
- Lambda: one expression only, no statements such as if blocks, loops or return
- Lambda: has no name, which makes error tracebacks less clear
- def: any number of statements, docstrings and type hints
- Rule of thumb: if it does not fit comfortably on one line, use def
Frequently asked questions
What is a lambda function in Python?
It is a small, unnamed function defined with the lambda keyword. It takes arguments and returns the value of a single expression.
Can a lambda have an if statement?
Not an if block, but it can use a conditional expression: lambda x: "even" if x % 2 == 0 else "odd".
How do I sort a list of dictionaries by a key in Python?
Use sorted(items, key=lambda d: d["price"]). Add reverse=True for descending order.