Functions
Lambdas
A lambda is a function expression. Assigning one to a name works, although def is usually clearer for reusable behavior.
Source
add_tax = lambda price: round(price * 1.08, 2)
print(add_tax(10))Output
10.8Lambdas are most idiomatic when passed directly to another function. sorted() calls this key function once for each item.
Source
items = [("notebook", 5), ("pen", 2), ("bag", 20)]
by_price = sorted(items, key=lambda item: item[1])
print(by_price)Output
[('pen', 2), ('notebook', 5), ('bag', 20)]A named function is better when the behavior should be reused or explained. It produces the same sort key, but gives the operation a name.
Source
def price(item):
return item[1]
print(sorted(items, key=price))Output
[('pen', 2), ('notebook', 5), ('bag', 20)]Notes
- Lambdas are expressions, not statements.
- Prefer
deffor multi-step or reused behavior. - Lambdas are common as
key=functions because the behavior is local to one call.
See also
- related: Functions
- prerequisite: Sorting
- next depth: Callable Objects
Run the complete example
Expected output
10.8
[('pen', 2), ('notebook', 5), ('bag', 20)]
[('pen', 2), ('notebook', 5), ('bag', 20)]
Execution time appears here after you run the example.