Lambda functions
These are Anonymous Functions that take multiple inputs and evaluate the output in a single statement. It has the following syntax:
lambda arguments : expression
Syntactic Sugar
A
lambda
expression creates a function object just like thedef
statement.
Lundh’s lambda Refactoring Recipe
If you find a piece of code hard to understand because of a lambda
, follow this refactoring procedure:
- Write a comment explaining what that
lambda
does. - Summarise that comment by a single statement.
- Convert the
lambda
expression into adef
expression with the name you found in (2) and the docstring with the comment you made in (1). - Remove the comment and use of the
lambda
statement with the new function.
Examples
Invert strings
lambda string : string[::-1]
Custom key to sort by
>>> test = [
>>> {"name": "julian", "age": 10},
>>> {"name": "sandra", "age": 8},
>>> {"name": "jemima", "age": 9}
>>> ]
>>> sorted(test, key = lambda entry : entry["age"])
[
{"name": "sandra", "age": 8},
{"name": "jemima", "age": 9},
{"name": "julian", "age": 10}
]