In Python, lambda function is called 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.
Lambda function is defined using lambda keyword along with parameter(s) name followed by a single statement. Please not that a lambda function can have many parameters but only one statement.
#Defining lambda lambda parameters: statement
x = lambda a, b : a * b print(x(3, 4))
12
Lambda function can be used anonymously inside another function, gives the flexibility of using the same function for different scenarios. In the below example, 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))
12.57 4 6
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.
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)
[1, 4, 9, 16, 25]
#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)
[1, 5, 7, 11, 13, 17, 19]
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)
60