In Python, lambda keyword is used to declare an anonymous function, which is called as Lambda functions. An anonymous function refers to a function declared with no name. They behave in the same way as regular functions that are declared using the def
keyword.
Syntax
Lambda function has following syntax
lambda arguments: expression
where lambda is keyword. It can have any number of arguments but only one expression. The expression is evaluated and returned.
The expression lambda parameters:
yields a function object. The unnamed object behaves like a function object defined with:
def <lambda>(arguments): return expression
Example
In below example, x and y are argument of lambda function, and x * y
is the expression that is evaluated and the result of the expression is returned.
product = lambda x, y : x * y print(product(2, 3)) # Output # 6
Like nested function definitions, lambda functions can reference variables from the containing scope. Below example lambda expression access the variable passed to function make_incrementor().
def make_incrementor(n): return lambda x: x + n incrementor = make_incrementor(100) print(incrementor(-50)) # Output # 50
Lambda expression return a function, which can be passed as function argument. In the below example, list is sorted based on second value of each element.
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) print(pairs) # Output # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]