To understand Lambda function we need to see a normal function in Python first, Lets begin:
Lets define a function first and then we will convert it to Lambda function
-----------------------
def add(x, y):
return x + y
print(add(2, 3))
-----------------------
Above function name is add, it expects two arguments x and y and returns their sum. Notice how we are printing and calling add function in last line
The output of above program is below:
-----------------------
5
-----------------------
# Now let us convert this function to Lambda function in Python
----------------------------------
add = lambda x, y : x + y
print (add(2, 3))
----------------------------------
The output of above code is below :
--------------
5
--------------
So what on earth is Lambda then ?
Basically lambda function is used for creating small, one-time and anonymous function objects in Python. In lambda x, y: x + y; x and y are arguments to the function and x + y is the expression which gets executed and its values is returned as output. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope.
Lets define a function first and then we will convert it to Lambda function
-----------------------
def add(x, y):
return x + y
print(add(2, 3))
-----------------------
Above function name is add, it expects two arguments x and y and returns their sum. Notice how we are printing and calling add function in last line
The output of above program is below:
-----------------------
5
-----------------------
# Now let us convert this function to Lambda function in Python
----------------------------------
add = lambda x, y : x + y
print (add(2, 3))
----------------------------------
The output of above code is below :
--------------
5
--------------
Basically lambda function is used for creating small, one-time and anonymous function objects in Python. In lambda x, y: x + y; x and y are arguments to the function and x + y is the expression which gets executed and its values is returned as output. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope.
No comments:
Post a Comment