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.
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
def Beats Named LambdasPEP 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.
return, for, if: blocks, and = assignments are forbidden inside lambda; only single expressions work.map() and filter() with lambdas: List comprehensions like [x * 2 for x in nums] are usually faster and easier to read.for loop capture the variable reference, not its current value, unless bound as a default argument lambda x=i: x.Yes. lambda: "ok" takes zero arguments, and lambda a, b: a + b takes two.
if / else expression?Yes, using ternary expression syntax: lambda x: "even" if x % 2 == 0 else "odd".
def?Switch to def whenever you reuse the function in two places, assign it to a variable, or need more than one short expression.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.