Python Tutorial · Functions · Lesson 25 of 42
Python Lambda
Small anonymous functions for sorting keys and quick callbacks.
Lambda functions
A lambda is a one-expression function without a name: lambda arguments: expression.
square = lambda x: x * x
add = lambda a, b: a + b
print(square(5))
print(add(2, 3))
Output
25 5
Where lambdas shine
Lambdas are most useful as short arguments to functions like sorted(), min(), max(), map() and filter():
products = [("pen", 1.5), ("book", 12.0), ("bag", 25.0)]
print(sorted(products, key=lambda p: p[1], reverse=True))
print(max(products, key=lambda p: p[1]))
print(list(map(lambda p: p[0].upper(), products)))
print(list(filter(lambda p: p[1] < 20, products)))
Output
[('bag', 25.0), ('book', 12.0), ('pen', 1.5)]
('bag', 25.0)
['PEN', 'BOOK', 'BAG']
[('pen', 1.5), ('book', 12.0)]If a lambda needs more than one simple expression, write a normal def function instead — it's easier to read, test and debug.
Test yourself
How many expressions can a lambda body contain?
OneTwoAny numberNone
Show answer
Answer: One