Lambda
expressions are used to create anonymous functions. Using keyword ‘lambda’ we
can create lambda expressions.
Syntax
lambda_expr ::=
"lambda" [parameter_list]: expression
lambda_expr_nocond
::= "lambda" [parameter_list]:
expression_nocond
test.py
def square(x): return x*x squareLambda = lambda x: x*x print(square(10)) print(squareLambda(10))
As you see
above code, both square, squareLambda doing exactly same operation, but defined
in two ways. ‘square’ is defined using the keyword ‘def’, ‘squareLambda’ is
defined using the keyword ‘lambda’.
As you see
the lambda definition, it don’t return any value like function. Lambda contains
an expression, which is returned as result to the caller.
test.py
def increment(n): return lambda x : x + n incrementBy2 = increment(2) incrementBy4 = increment(4) incBy2 = lambda x : x + 2 incBy4 = lambda x : x + 4 print(incrementBy2(100)) print(incrementBy4(100)) print(incBy2(100)) print(incBy4(100))
$ python3
test.py
102
104
102
104
In the above
code function ‘increment’ creates anonymous functions on the fly and return
them.
incrementBy2
= increment(2) is same as incrementBy2 = lambda x : x + 2.
Another
example to calculate sum of two numbers using lambda expressions.
test.py
sum = lambda x, y : x+y print(sum(10, 20)) print(sum(1034, 2230)) print(sum(10342, 32450))
$ python3
test.py
30
3264
42792
Referred Articles
No comments:
Post a Comment