Keywords and Expressions
lambda — Anonymous function expression
Create a function object from a parameter list and one expression. Calling it evaluates that expression and returns its value. Lambda supports ordinary argument binding and defaults, but its body cannot contain statement suites or parameter annotations. Captured free names are resolved when the function runs, so closures created in a loop may observe the final binding unless a default or separate scope captures a value. Prefer def for complex named behavior.
Formal Syntax & Structure
python syntaxpython
lambda [parameters]: expressionParameters & Attributes
| Name | Type | Description |
|---|---|---|
| parameters | parameter list | Optional arguments and defaults. |
| expression | expression | Single function body expression. |
Return Value
function
A function object; the expression is evaluated when called.
Working Example
Example Snippetpython
items = [("pen", 3), ("book", 1), ("bag", 2)]print(sorted(items, key=lambda item: item[1]))print((lambda x, y=2: x * y)(5))