Functions

Lambdas

lambda creates small anonymous function expressions.

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.8
lambda x: x + 1paramsexpression
A lambda is a function literal: parameters before the colon, a single expression after, no statement body.

Lambdas 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

See also

Run the complete example

Example code

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.