Python – Lambda Function

In Python, a lambda function is sometimes known as an anonymous function since it has no name. An anonymous function is declared using the lambda keyword rather than the def keyword.

Create lambda Function

The Python – Lambda Function is defined by using the lambda keyword, followed by the name of the parameter(s) and a single statement. A lambda function can contain a lot of parameters, but only one statement.

Syntax

#Defining lambda
lambda parameters: statement

Example:

A lambda function is defined in the example below, which accepts two parameters and returns the product of the provided arguments.

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

The output of the above code will be:

12

Use of Lambda function

The flexibility of utilising the same function for multiple contexts is provided by the Lambda function’s ability to be utilised anonymously inside another function.

Example:

The lambda function is used in the example below to transform a user-defined ‘area’ function to compute the area of a 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

Python has a number of built-in functions that take a function as an argument. In such circumstances, a lambda function can be used instead of defining a function, as long as it only has one statement. Map, reduce, and filter are a few examples of built-in functions.

Example: Lambda function with the 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

Reduce function must be imported from the functools module in order to work..

#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

Also Read: Java – Constructors

Leave a Reply

Your email address will not be published.