To define anonymous functions we can use lambda
key word.
Syntax
lambda arguments: expression
Example
Takes one argument x,add 5 to x and returns the result.
f = lambda x: x + 5print(f(10))
Output
15
Example
f = lambda x, y : x + yprint(f(10, 20))
Output
30
The above example can also be written as bellow
(lambda x, y: x + y)(10,20)
Where to Use lambda function
The lambda function can be passed as an argument to another function.
def func(n):return lambda x: x + n
We can use the same function to define a function that always doubles the number we input.
def func(n):return lambda x: x + ndouble = func(2)print(double(10))
Output
20
We can use the same function to define another function that always triples the number we input.
def func(n):return lambda x: x + ntriple= func(3)print(triple(10))
Output
30
Here the same function func() is used for both the functions to make double and triple of the inputted number.
Comments
Post a Comment