Python Lambda
A lambda is a modest anonymous function.
A lambda can only take a single expression and use a number of arguments.
Syntax:-
lambda arguments : expression
The expression is run and the result will be returned :
Example 1 :- Add 10 to argument a
, and return the result :
x = lambda a: a + 10
print(x(5))
Output :-
The functions of Lambda can take any number of arguments :
Example 2 :- Multiply argument a and return the outcome with argument b :
x = lambda a, b: a * b
print(x(5, 6))
Output :-
Example 3 :- Resume the arguments a, b, and c and return them :
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
Output :-
Related Links
Why Use Lambda Functions?
When used as an anonymous function within another function, the power of lambda is best demonstrated.
Say, you have an argument definition for the function, and this argument is multiplied by an unknown number :
def myfunc(n):
return lambda a : a * n
Example 1 :- Use this function definition to create a function which always doubles the send number :
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output :-
Example 2 :- Use the same concept in order to create a function that triples your number :
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Output :-
Example 3 :- To perform both functions in the same program to use the same function definition :
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output :-
33
When an anonymous function is needed for a brief length of time, use lambda functions.
Related Links