Explain lambda function in Python

OR Explain Anonymous Function in python

OR Lambda function along with map and filter function

OR How map can be used in Python program? Explain with a suitable example

OR Differentiate between filter and map in Python using example.


In Python, an anonymous/lambda function is a function that is defined without a name. While normal functions are defined using the d​ ef​ keyword in Python, anonymous
functions are defined using the ​lambda​ keyword.
Hence, anonymous functions are also called lambda functions.
Syntax​: lambda arguments: expression
Lambda functions can have any number of arguments but only one expression
Program:

x = lambda a: a + 10 
print(x(5))

Output​: 15

Use of Lambda Function in python :

We use lambda functions when we require a nameless function for a short period of time.
Lambda functions are used along with built-in functions like filter(), map() etc.

Lambda function with filter():

The filter() function in Python takes in a function and a list as arguments.

Here is an example use of filter() function to filter out only even numbers from a list.
Program​:

my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list)) 
print(new_list)

Output​: [4, 6, 8, 12]

Lambda function with filter():

The map() function in Python takes in a function and a list.

Here is an example use of map() function to double all the items in a list.
Program:

my_list = [1, 5, 4, 6]
new_list = list(map(lambda x: x * 2 , my_list)) 
print(new_list)

Output: [2, 10, 8, 12]

To Learn more about Python, Click Here

Click here To Follow on pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *