Definition
Python have another way to create functions.
In this way, python uses lambda keyword to create a function.
Lambda function can take any number of arguments and it evaluates the expression and return the result which we can store using a variable.
Syntax
lambda arguments : expression
Example 1
x = lambda y : y * 2print(x(5))
Output
10
Here, we have created a lambda function and give only one argument as y and the expression is y * 2.
We are storing the result to x.
We call the lambda function inside print statement by giving argument value 5 to x.
Example 2
x = lambda y,z :y * z + 2print(x(5,10))
Output
52
Here, we created a lambda function which takes two arguments y, z, and returns the result of expression y * z + 2.
Example 3
a = lambda x,y,z : x + y * z + 2print(a(5,10,12))
Output
127
Here, we have created a lambda function which takes three arguments and return the result after evaluation.
We are not restricted to number of arguments, we can create a lambda function which can take as much arguments as we want.
Python Function Vs Python Lambda
# multiply two numbers using lambdaa = lambda x,y: x*yprint(a(3,10))# outputs 30
# multiply two numbers using functiondef mul(x, y):return x*yprint(mul(3, 10))# outputs 30
Lambda inside Functions
Power of lambda functions shown inside Python Functions as anonymous functions.
Example 1
# function argument is xdef mul(x):# lambda argument is yreturn lambda y: x * y# function argument value = 5result = mul(5)# lambda argument value = 4print(result(4))
Output
20
Example 2
# function argument is xdef mul(x):# lambda argument is yreturn lambda y: x * ymyList = [10, 20, 30, 40, 50]for i in myList:# function argument is i i.e. myList itemsresult = mul(i)# lambda argument is 10print(result(10))
Output
100200300400500