lambda creates a function object without giving it a name via def, restricted to a single expression whose result is automatically returned — there's no block body, no statements, and no explicit return keyword. Lambdas are most commonly passed directly as the key or condition argument to functions like sorted(), max(), map(), and filter(), where defining a full named function would be unnecessary ceremony for a one-line operation.
1Understanding lambda Functions
lambda creates a function object without giving it a name via def, restricted to a single expression whose result is automatically returned — there's no block body, no statements, and no explicit return keyword. Lambdas are most commonly passed directly as the key or condition argument to functions like sorted(), max(), map(), and filter(), where defining a full named function would be unnecessary ceremony for a one-line operation.
If a lambda is complex enough that it's hard to read on one line, or if it's used in more than one place, define it as a proper named function with def instead — that's exactly the situation lambda isn't meant for.
square = lambda x: x ** 2
print(square(6))2Practical Example
Here is a real-world application of lambda Functions showing how it is used in production Python code.
people = [("Alice", 30), ("Bob", 25), ("Carol", 35)]
by_age = sorted(people, key=lambda person: person[1])
print(by_age)3Best Practices
Follow these guidelines when working with lambda Functions:
1. Use lambda for short, one-off functions passed inline to sorted(), map(), filter(), or similar, not for logic you'll reuse elsewhere
2. Assign a def function a real name instead of binding a lambda to a variable name — PEP 8 explicitly recommends def for anything you're going to bind to a name
3. Keep lambda bodies to a single simple expression; reach for def as soon as you need multiple statements or a docstring
Tip: If a lambda is complex enough that it's hard to read on one line, or if it's used in more than one place, define it as a proper named function with def instead — that's exactly the situation lambda isn't meant for.
square = lambda x: x ** 2
print(square(6))