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
lambda x: x ** 2does the same asdef square(x): return x ** 2. There is noreturnkeyword: the expression after the colon is the return value.- A lambda can hold only one expression. It cannot contain statements such as
ifblocks, loops or assignments. - Giving a lambda a name, as above, is fine for learning. In real code the style guide (PEP 8) prefers
deffor any function you give a name to.
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.