In Python programming, an anonymous function is a type of function without any name. Like the def keyword in normal function definitions, the lambda keyword is used to create small anonymous functions.
Lambda functions can take any number of arguments but only one expression. This expression is evaluated and returned. These functions can be used wherever function objects are needed. We normally use lambda functions when an anonymous function is required for a short period of time.
It has the following syntax:
lambda arguments: expression
Let us look at this coding example and try to compare between a normal function and a lambda function. This is a program that returns the square of a given integer value:
# Normal function
# Lambda function
val = lambda b: b*b
In the above coding example,
lambda b: b * b is the lambda function. Here b is the argument and
b * b is the expression that gets evaluated and returned.
This function does not have any name or return statement. Still, it returns a function object which is assigned to the variable named val. We can now consider it as a normal function. The statement
val = lambda b: b * b
is thus equivalent to:
def val(b): return b * b
We can send any number of arguments in the lambda function:
val = lambda x, y, z : x * y * z
print("Value:", val(8, 9, 10))
Significance of Lambda Functions:
The power of lambda is better illustrated when we use it as an anonymous function inside another function. We can use the same function definition to make a function that always doubles or triples the number we pass as an argument:
return lambda x : x * y
double = function(2)
triple = function(3)