Python: Lambda(Anonymous) Function

In python, anonymous function is a function that is defined without a name. A lambda function can take any number of arguments, but can only have one expression. It can be used wherever function objects are required.  

For Example: The def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.

Syntax:

lambda arguments: expression

Example:

a = lambda a : a ** 4 
print(a(3))

Output: 81

In the example, lambda a : a ** 4 is the lambda function. Here a is the argument and a ** 4 is the expression that gets evaluated and returned.

This function has no name. It returns a function object which is assigned to a. We can now call it as a normal function. 

Use of Lambda Function in Python

Lambda functions is used when we require a nameless function for a short period of time.

1. Using lambda() Function with filter():

The filter() function in Python takes in a function and a list as arguments. This function is used to filter out all the elements of a sequence for which the function returns True.

Example:

list_1 = [1,2,3,4,5,6,7,8,9,0]
list_2 = list(filter(lambda a : (a % 2 != 0), list_1))
print(list_2)

Output: [1, 3, 5, 7, 9]

2. Using lambda() Function with map():

It takes in a function and a list as arguments. This function is used to called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. 

Example:

list_1 = [1,2,3,4,5,6,7,8,9,0]
list_2 = list(map(lambda a : (a ** 2), list_1))
print(list_2)

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 0]

Tags