Python Lambda
Abdulmutalib Idris
Head of IT and Media / Full Stack Developer @ Agro Preciso LTD
Is a function that take as many arguments as possible but can only have one expression. They are also consider anonymous as they have no name. The expression will be executed and the result returned.
Syntax
lambda arguments : expression
Example: lets add 100 to an argument in lambda as follow
y = lambda x : x + 100
print(y(17))
Example: lets multiply two argument as follow
a = lambda x, y : x * y
print(a(4, 12))
Let see how lambda and normal function will find the cube of a number:
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print("Using function defined with def keyword, cube:", cube(5))
print("Using lambda function, cube:", lambda_cube(5))
Python Lambda Function with if-else
Here we are using the Max lambda function to find the maximum of two integers.
max = lambda a, b : a if(a > b) else b
print(max(1, 2))
Difference Between Lambda functions and def defined function
领英推荐
Using lambda function
def defined function
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number you send in:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))