Python anonymous and lambda function; Through this tutorial, i am going to show you what is anonymous & Lambda function in python and how to use this function in python.
What is Lambda/Anonymous Function in Python
In Python programming language, anonymous function is a function that is also known as a lambda function. defined without a name. Functions that are defined without a name and without def keyword are also called anonymous function or lambda function.
Syntax of Lambda Function in python
A lambda/anonymous function in python has the following syntax.
lambda arguments: expression
Example of Lambda Function in python
Let’s take a simple example of the Lambda Function in python. So that you will understand how to make it and how to use it:
# Python Program to display the uses of lambda functions myFunc = lambda x: x * 2 # Output: 10 print(myFunc(5))
In the above lambda function program, lambda x: x * 2 is the simple lambda function. Here x is the argument of lambda function in python and x * 2 is the expression of lambda function program.
This function has no name. It returns a function object which is assigned to the identifier myFunc. you can now call it as a normal function.
The statement
myFunc = lambda x: x * 2
It is almost the same as the function below:
def myFunc(x): return x * 2
Use of Lambda Function in python
Whenever a function is created for a short time and that too without defining its name. At that time you do the lambda function.
Let us now use the Lambda function with some Python in-built functions ( filter()
, map()
) and take the example:
Example: python lambda function with filter
First of all, you should know that the Python filter function takes some arguments.
Now create a program using filter () and lambda function, in this function you will pass a list and this function will give us a list of even numbers from given list by using filter and lambda function.
# python lambda function list filter a = [1, 5, 4, 6, 8, 11, 3, 12] b = list(filter(lambda x: (x%2 == 0) , a)) print(b)
Output
[4, 6, 8, 12]
Example: python anonymous/lambda function map
First of all, you should know that the Python map function takes some arguments.
Now create a program using map () and lambda function, in this function and will pass a list and this function will double the number of the given list using map and lambda function.
# python lambda function list map a = [2, 4, 6, 8, 10, 12] b = list(map(lambda x: x * 2 , a)) print(b)
Output
[4, 8, 12, 16, 20, 24]
Example: python lambda function with reduce
First of all, you should know that the Python reduce function takes some arguments.
Now create a program using reduce() and lambda function, in this function and will pass a list and this function will sum of the given number list using reduce() and lambda function.
# python lambda function list filter a = [1, 5, 4, 6, 8, 11, 12] sum = reduce((lambda x, y: x + y), a) print(sum
Output
47