Python Anonymous Function With Examples

Welcome to Python anonymous function tutorial. In the previous tutorial we learned about Python Recursion.

Python Anonymous Function

Python Anonymous function is a function which has no name. Therefore, we can use Python Anonymous function for a small scope of program. Normally, we define Python function using def keyword. But we define anonymous function using lambda keyword. The basic structure of an anonymous function is given below.

Look closely, that while taking one or more arguments the anonymous function has only one expression. So, if we want to make a function which will calculate sum of two number. The following code will do so;

But, we can convert this function to anonymous function. The code will be like this

Why Should We Use Python Anonymous Function

It may seem that we can replace an anonymous function with a regular function. Then, why should we use an anonymous function? Firstly, you may need to do a single task repeatedly across your scope. Therefore, you need a temporary function to do that. With this intension, lambda/anonymous function can help you. Because, anonymous function is valid in between the scope while a regular function is valid in the program.

Expression or Statement

The main confusion about implementing an anonymous function is, not having the ability of differentiating between an expression and a statement. Basically, a statement returns nothing while an expression produces at least one value. Simple mathematical expression like addition, multiplication, division are expressions and can be used in lambda/anonymous function. So, you have to add an expression so that the result of the expression can be returned through the lambda/anonymous function.

Some Use of Lambda/Anonymous Function

Now, we are going to see some common use of lambda. By using map() and filter() function we can change a list using anonymous function. For example, we want increment all the numbers in a list by n. To do so, the code should be like this

The output will be

Python Anonymous function

Similarly, if we want to store the common elements of two list into new list, we can use filter. To check if the an element is in List2, we used lambda function. The example code is given below

The output of the above program will be

Python Anonymous function

So, that’s all about Python Anonymous Function. Hope that, Python Anonymous Function is clear to you now. For any further query, feel free to use the comment box. Good Luck!

By admin

Leave a Reply