Python lambda Keyword
The Python lambda keyword is used to build anonymous function, a function without a name. An anonymous function is not declared by def keyword, rather it is declared by using lambda keyword.
Syntax
#Defining lambda lambda parameters: statement
Example:
In the example below, a lambda function is defined which takes two arguments and returns product of the passed arguments.
x = lambda a, b : a * b print(x(3, 4))
The output of the above code will be:
12
Use of Lambda function:
Lambda function can be used anonymously inside another function, gives the flexibility of using the same function for different scenarios. In the example below, lambda function is used to convert user-defined 'area' function to calculate area of circle, square and rectangle.
Example:
In the example below, lambda function is used to convert user-defined 'area' function to calculate area of circle, square and rectangle.
def area(n): return lambda a, b=1 : n * a * (b if b != 1 else a) circle_area = area(22/7) square_area = area(1) rectangle_area = area(1) print(circle_area(2)) print(square_area(2)) print(rectangle_area(2, 3))
The output of the above code will be:
12.571428571428571 4 6
❮ Python Keywords