How to write lambda function in python programming?
We use lambda
keyword for creating lambda function.
Syntax : lambda parameter1,parameter2,..:expression
We have to write single expression in lambda function. Lets see some examples
1st if we don’t want to reuse the lambda function then we will write like this
avg2 = (lambda num1,num2:(num1+num2)/2)(10,50)
print(avg2)
Output : 30
Explanation : Here we have saved the lambda function value in the variable name avg
. So we can not reuse the function here.
2nd if we want to reuse the lambda function , we will write:
avg = lambda num1,num2:(num1+num2)/2
print(avg(10,20));
print(avg(10,65));
Output :
15
37.5
Explanation : Here we have saved the lambda function definition in the variable name avg
and reusing this variable by providing parameter values.