Python - Add Two Numbers using Lambda Function
Add Two Numbers using Lambda Function in Python
Two add two given numbers using a lambda function in Python, we have to define a lambda function that can take two numbers as arguments, and return their sum.
Now, let us define the lambda function.
We know that the lambda function starts with the lambda keyword.
lambda
This lambda function must have two parameters, for the two input numbers. Let us assume that these numbers are a
, and b
.
lambda a,b
The lambda function must return the sum of two given numbers.
lambda a,b: a+b
Here it is! Our lambda function that can take two numbers, and return their sum.
Examples
1. Find sum of 5 and 3 using lambda function
In this example, we shall use the lambda function that we defined above, and find the sum of two numbers. We shall assign the lambda function to a variable, say sum
, so that we can call the lambda function using that name.
Python Program
sum = lambda a,b: a+b
num1 = 5
num2 = 3
result = sum(num1,num2)
print(f"Sum of {num1} and {num2} is {result}.")
Output
Sum of 5 and 3 is 8.
Summary
In this tutorial, we learned how to define a lambda function to find the sum of given two numbers, with an example program.