Lambda/Anonymous Function in Python Programming
Function in Python
In this lesson, we will understand what is Lambda or anonymous Function in Python Programming and how to create them along with some examples.
What is Lambda or Anonymous Function in Python?
A Lambda Function in Python is an anonymous function. An anonymous function is a function that has no name.
Generally, a function in python is defined using the keyword def. But an anonymous function is defined with the keyword lambda.
A Lambda Function can have any number of arguments but the body of the function must contain only a single line of expression and not more than that.
Syntax of Creating a Lambda Function
To create a lambda function, we have to use the keyword lambda, as shown below.
Syntax of Lambda Function
variable_name = lambda argument1, argument2,... : expression
Now we know the syntax of creating a lambda function. Let's see some examples to make it more clear.
Program to create a lambda function that will return the square of a given number.
Lambda Function Example 1
square = lambda n : n * n print(square(2))
In the above program, we have declared a lambda function that takes a number in argument n and returns its square. The function is stored in the variable square.
On the second line of the program, we have called the lambda function square inside the print() function and passed the number 2. The lambda function calculates the square of the given number and returns the output, which is printed on the screen by the print() function.
Program to create a lambda function that will accept 3 numbers and return its sum.
Lambda Function Example 2
sum = lambda a, b, c : a + b + c print(sum(2,8,5))
In the above program, we have declared a lambda function that takes 3 numbers in argument a, b and c and returns its sum. The function is stored in the variable sum.