Inline callback
Pass a short transformation or key function directly to an API that accepts a callable.
Python · Const
A lambda expression creates an anonymous function object from an optional parameter list and one expression. Calling it returns the value produced by that expression.
A lambda expression creates a function object without assigning it a name. Its parameter list is optional, and its body is exactly one expression whose evaluated value becomes the function call's result; it cannot contain statements or annotations.
lambda [parameter_list]: expression| Name | Type | Description |
|---|---|---|
parameter_list | parameters | An optional ordinary function parameter list, using the syntax described for function definitions. |
A function object whose call result is the value of the body expression.
def whose body returns the lambda expression's value.numbers = [3, 1, 2]
squares = list(map(lambda n: n * n, numbers))
print(squares)The lambda accepts one number and returns its square; map applies it to every item.
Pass a short transformation or key function directly to an API that accepts a callable.
Create a compact callable for a simple calculation without a separate named definition.
The syntax is lambda followed by an optional parameter list, a colon, and one expression. Evaluating it produces a function object, and calling that function returns the expression's value.
Follow-up: Can a lambda contain an assignment statement or a return statement? No: its body is restricted to an expression, so use def for statement-based logic.
A lambda can omit parameters, accept parameters, and use the normal parameter-list rules. For example, lambda a, b: a + b creates a two-argument function.
Follow-up: How would you support defaults or keyword-only parameters? Use the corresponding forms permitted in a normal function parameter list.
def?Lambda expressions are useful when a small function object is needed inline, such as passing a transformation to map. The resulting object behaves like a function defined with def, except the lambda syntax is limited to one expression and does not provide a named definition.
Follow-up: When should a regular function be preferred? Prefer def when the logic needs statements, annotations, or a clearer reusable definition.
function definitionsparameter listsfunction objectexpression