Python Lambda
Python Lambda: Inline One-Expression Callbacks
A Python lambda is a small anonymous function written on a single line without a def header. It takes any number of arguments, evaluates one expression, and automatically returns the result.
Developers reach for lambda when passing a tiny sorting or key-extraction rule into functions like sorted(), min(), max(), or GUI event callbacks.
Practical Uses with sorted() and min()
Instead of writing a throwaway 2-line helper function for a single sort call, pass a lambda directly to the key= parameter.
products = [
{"name": "Keyboard", "price": 75},
{"name": "Mouse", "price": 35},
{"name": "Monitor", "price": 240},
]
by_price = sorted(products, key=lambda item: item["price"])
cheapest = min(products, key=lambda item: item["price"])
print([p["name"] for p in by_price]) # ['Mouse', 'Keyboard', 'Monitor']
print(cheapest["name"]) # Mouse
Why def Beats Named Lambdas
PEP 8 advises against assigning a lambda to a variable (square = lambda x: x * x). A normal def statement gives the function a real name in tracebacks and supports docstrings and multi-line logic.
Common Mistakes to Avoid
- Trying to put statements inside a lambda:
return,for,if:blocks, and=assignments are forbidden insidelambda; only single expressions work. - Overusing
map()andfilter()with lambdas: List comprehensions like[x * 2 for x in nums]are usually faster and easier to read. - Late-binding inside loop lambdas: Lambdas created inside a
forloop capture the variable reference, not its current value, unless bound as a default argumentlambda x=i: x.
Frequently Asked Questions
Can a lambda take zero or multiple arguments?
Yes. lambda: "ok" takes zero arguments, and lambda a, b: a + b takes two.
Can a lambda contain an if / else expression?
Yes, using ternary expression syntax: lambda x: "even" if x % 2 == 0 else "odd".
When should I replace a lambda with def?
Switch to def whenever you reuse the function in two places, assign it to a variable, or need more than one short expression.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.