20220225 180317
#Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can
only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
x = lambda a : a * 10
print(x(5))
x = lambda a,b,c : a * b + c
print(x(5,10,20))
-------------------------------------------
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
def myfun(n):
print("n=",n)
return lambda a : a * n
n_val = myfun(4)
print(n_val(2))
-output--
n= 4
8