PythonMastery
Python programs · Functions · beginner

Lambda function in Python

A lambda is a small function written as one expression. See how to write one and where it is useful: as the key for sorted(), max() and min().

A lambda is a small function without a name, written as one expression: lambda arguments: expression. It returns the value of the expression.

The program

python
square = lambda x: x ** 2
add = lambda x, y: x + y
is_even = lambda x: x % 2 == 0

print(square(5))
print(add(3, 4))
print(is_even(8))
output
25
7
True

How it works

Where lambdas are useful

A lambda is most useful when another function needs a small function for a short time. The key argument of sorted(), max() and min() is the most common case:

python
people = [("Ada", 36), ("Linus", 54), ("Grace", 85), ("Alan", 41)]

by_age = sorted(people, key=lambda person: person[1])
print(by_age)

oldest = max(people, key=lambda person: person[1])
print(oldest)

words = ["banana", "Kiwi", "apple", "Cherry"]
print(sorted(words, key=lambda w: w.lower()))
output
[('Ada', 36), ('Alan', 41), ('Linus', 54), ('Grace', 85)]
('Grace', 85)
['apple', 'banana', 'Cherry', 'Kiwi']

key is called once for each item, and the items are compared by what it returns. Without key=lambda w: w.lower(), the words that start with a capital letter would sort before all the lowercase ones.

Learn the idea: Lambda & Functional Programming, Functions & Scoping