lambda
lambda makes a small, nameless function in one expression. It is most useful as a key for sorted(), min(), max() and similar.
lambda parameters: expressionlambda x: x * 2 is a function written as an expression: the names before the colon are its parameters, and the expression after it is what it returns. There is no return keyword and no name.
Its main job is to pass a tiny piece of logic to another function, such as the key of sorted(), max() or min(), without writing a full def that you only use once.
A lambda can only hold one expression: no statements, no loops, no assignments. If you need more, or if you are about to give the lambda a name, use def (functions) instead.
Return value
A function object. Calling it returns the value of the expression.
Examples
1A first lambda
double = lambda x: x * 2
print(double(7))
print((lambda a, b: a + b)(3, 4))14 7
Storing a lambda in a variable works, but style guides prefer a def in that case.
2Sort by a key
people = [("Lea", 31), ("Arjun", 25), ("Zoe", 40)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age)
words = ["kiwi", "fig", "banana"]
print(sorted(words, key=lambda w: len(w)))[('Arjun', 25), ('Lea', 31), ('Zoe', 40)]
['fig', 'kiwi', 'banana']3Find the cheapest item
products = [
{"name": "lamp", "price": 35},
{"name": "chair", "price": 49},
{"name": "mug", "price": 8},
]
cheapest = min(products, key=lambda p: p["price"])
print(cheapest["name"])mug
4With map() and filter()
prices = [10, 25, 4, 60]
with_tax = list(map(lambda p: p * 1.1, prices))
print([round(p, 2) for p in with_tax])
big = list(filter(lambda p: p > 20, prices))
print(big)[11.0, 27.5, 4.4, 66.0] [25, 60]
A list comprehension often does the same job and reads more easily.
5A conditional expression inside
label = lambda n: "even" if n % 2 == 0 else "odd"
for n in [3, 8]:
print(n, label(n))3 odd 8 even
Common mistakes
Lambdas in a loop all see the last value
A lambda looks up outside variables when it runs, not when it is made. Lambdas created in a loop then all use the final loop value. Bind the value with a default argument.
adders = [lambda x: x + n for n in range(3)]
print([f(10) for f in adders])
adders = [lambda x, n=n: x + n for n in range(3)]
print([f(10) for f in adders])[12, 12, 12] [10, 11, 12]
Trying to put statements in a lambda
lambda x: print(x); return x or lambda x: y = x are not allowed. Only one expression fits. Write a def for anything longer.
Questions people ask
When should I use lambda instead of def?
Use lambda for a short expression passed straight to another function. Use def when the function needs a name, several lines, or a docstring.
Can a lambda have more than one argument?
Yes: lambda a, b: a * b. It can also have defaults and *args.
Can a lambda have if / else?
Only as a conditional expression: lambda n: "big" if n > 10 else "small". An if statement is not allowed.