Python Lambda Functions

Python Lambda function is known as the anonymous function that is defined without a name. Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by using the lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of expression.

The anonymous function contains a small piece of code. It simulates inline functions of C and C++, but it is not exactly an inline function.

The syntax to define an anonymous function is given below.

Syntax

It can accept any number of arguments and has only one expression. It is useful when the function objects are required.

Consider the following example of the lambda function.

Example 1

Output:

 at 0x0000019E285D16A8>
sum =  30

In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument and a+10 is an expression. The given expression gets evaluated and returned the result. The above lambda function is same as the normal function.

Example 2

Multiple arguments to Lambda function

Output:

Enter the number:10
10 X 1 = 10 
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

The lambda function is commonly used with Python built-in functions filter() function and map() function.

Use lambda function with filter()

The Python built-in filter() function accepts a function and a list as an argument. It provides an effective way to filter out all elements of the sequence. It returns the new sequence in which the function evaluates to True.

Consider the following example where we filter out the only odd number from the given list.

Output:

(37, 41, 123, 29)

Using lambda function with map()

The map() function in Python accepts a function and a list. It gives a new list which contains all modified items returned by the function for each item.

Consider the following example of map() function.

Output:

(100, 400, 900, 1600, 2500, 3600)

Next TopicPython Files Io




Hot Tutorials

Contact US

Email:jjw.quan@gmail.com

Python Lambda Functions
10/30