Lambda Function in Python Programming
Lambda Function in Python: Lambda function is also known as an anonymous function. Anonymous function means, function without a name. We used the “def” keyword to define a function but the “lambda” keyword is used to define the lambda function.
Syntax of Lambda Function:
lambda arguments : expression
- The lambda function can have multiple arguments but it should have only single expressions.
- Lambda function is limited to a single expression only.
- Lambda function does not have any name.
- In the Lambda function, there is no need to write the return function.
Example 1: Program to find the square of five using normal function.
#Square of 5 using normal function x = 5 def fncn(): i = x*x print(i) fncn()
Example 2: Program to find the square of five using normal function.
#Lambda function with single argument x = lambda a : a*a result = x(5) print(result)
If you are learning about lambda function first time, then it is OK if you are facing difficulty in understanding. Don’t worry I will try to make you more clear by step by step and easy approach.
Let’s take the same example, Program to find the square of a number(5).
Step 1). a : a*a
just say a i want the square of a*a ie. (a:a*a)
Step 2). lambda a : a*a
Now we are working with a lambda function, so we need to name our arguments as lambda ie. (lambda a:a*a)
Step 3). x = lambda a : a*a
Now we will assign or store the value in a variable x ie. ( x = lambda a:a*a)
So our complete lambda function is : x = lambda a:a*a
The rest of the process is the same to call a function by passing arguments. Here we have used only one argument that’s why we only pass one argument ie. x(5) . Next we print the output accordingly.
Example 3: In this example I will show you how to use more than one argument in lambda function. Lambda function is also called as lambda expression.
Program to find sum of two numbers using lambda expression:
#Lambda function with two arguments x = lambda a,b : a+b result = x(5,7) print(result)
Note: A very important point to remember is that lambda function can have any number of arguments but have single expression.
Example 4: Program to return two values or result using lambda function:
#Lambda function with two arguments returning two values. x = lambda a,b : (a+b,a-b) result1 , result2 = x(7,5) print(result1) print(result2)