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 * 2 print(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 + 2 print(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 + 2 print(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 lambda a = lambda x,y: x*y print(a(3,10)) # outputs 30
# multiply two numbers using function
def mul(x, y):
return x*y
print(mul(3, 10))
# outputs 30Lambda inside Functions
Power of lambda functions shown inside Python Functions as anonymous functions.
Example 1
# function argument is x
def mul(x):
# lambda argument is y
return lambda y: x * y
# function argument value = 5
result = mul(5)
# lambda argument value = 4
print(result(4)) Output
20
Example 2
# function argument is x
def mul(x):
# lambda argument is y
return lambda y: x * y
myList = [10, 20, 30, 40, 50]
for i in myList:
# function argument is i i.e. myList items
result = mul(i)
# lambda argument is 10
print(result(10))Output
100 200 300 400 500