In Python, lambda functions are small, anonymous functions defined with the lambda keyword. Unlike functions defined with def, lambdas are expressions, meaning they yield a function object directly. They are restricted to a single expression; they cannot contain statements or annotations.
Syntax
The syntax is lambda arguments: expression. The expression is evaluated and returned. They are most idiomatic when used as throwaway functions for callbacks or key functions.
Common Use Cases
Lambdas shine when passed as arguments to higher-order functions like sorted(), map(), and filter().
Readability Limits
While concise, lambdas can hurt readability if they become complex. Python's style guide (PEP 8) discourages assigning lambdas to variables (use def instead). If a lambda expression barely fits on one line, it should probably be a named function.
The Operator Module
For simple operations like retrieving an item or attribute, the operator module is often faster and more readable than a lambda.