Python Tutorial Python Advanced Python References Python Libraries

Python - Lambda Function



In Python, lambda function is also termed as anonymous function and it is a function without a name. An anonymous function is not declared by def keyword, rather it is declared by using lambda keyword.

Create lambda Function

Lambda function is defined using lambda keyword along with parameter(s) name followed by a single statement. Please note that a lambda function can have many parameters but only one statement.

Syntax

#Defining lambda
lambda parameters: statement

Example:

In the example below, a lambda function is defined which takes two arguments and returns product of the passed arguments.

x = lambda a, b : a * b
print(x(3, 4))

The output of the above code will be:

12

Use of Lambda function

Lambda function can be used anonymously inside another function, gives the flexibility of using the same function for different scenarios.

Example:

In the example below, lambda function is used to convert user-defined 'area' function to calculate area of circle, square and rectangle.

def area(n):
  return lambda a, b=1 : n * a * (b if b != 1 else a)

circle_area = area(22/7)
square_area = area(1)
rectangle_area = area(1)

print(circle_area(2))
print(square_area(2))
print(rectangle_area(2, 3))

The output of the above code will be:

12.571428571428571
4
6

Lambda function with built-in function

There are several built-in function in Python which requires function as argument. Instead of creating a function, lambda function can be used in such cases effectively provided it must have single statement. Few of such built-in functions are map, reduce and filter etc.

Example: lambda function with map function


MyList = [1, 2, 3, 4, 5]
#Creating a map function using lambda function
#which returns square of each element
NewList = list(map(lambda i: i*i, MyList))

print(NewList)

The output of the above code will be:

[1, 4, 9, 16, 25]

Example: lambda function with filter function


#Removing all elements from range(1,21)
#which are multiples of 2 or 3
NewList = list(filter(lambda i: (i%2!=0) and (i%3!=0), range(1,21)))

print(NewList)

The output of the above code will be:

[1, 5, 7, 11, 13, 17, 19]

Example: lambda function with reduce function

for reduce function to work, it must be imported from functools module.

#lambda function is used to find out max element of a set
from functools import reduce
MySet = {10, 20, 30, 40, 50, 60} 
max_num = reduce(lambda a, b: a if a > b else b, MySet)

print(max_num)

The output of the above code will be:

60