Lambda Functions
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
def square(a):
return a*a;
# Lambda function
val = lambda b: b*b
print(val(9))
print(square(7))
Output:
81
49
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
Multiple arguments:
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))
Output:
Value: 720
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:
def function(y):
return lambda x : x * y
double = function(2)
triple = function(3)
print(double(10))
print(triple(20))
Output:
20
60