A Python lambda function is a small anonymous function without a name. It is defined using the lambda
keyword and it can take any number of arguments, but it can only have one expression.
Here is an example of a simple lambda function that takes two arguments and returns their sum
add = lambda x, y: x + y
# which is same as
def sum(x1,x2):
return x1+x2
add = sum(x,y)
Lamda Examples
We can apply the lambda
function to any argument by surrounding both the lambda function and the argument in parenthesis as shown below.
>>> (lambda x: x + 5)(2)
7
>>> (lambda x, y = 5: x + y)(2)
7
>>> (lambda x, y: x + y)(2, 3)
5
We can also define the lambda
function first and apply it to any arguments as shown below
add = lambda x, y: x + y
add(2, 3)
# 5
Lambda functions can take other functions as arguments or return one or more functions.
# defining functions
def div(x, y):
if(y!=0):
return x/y
else:
return "Division by Zero"
def add(x, y):
return x + y
def sub(x, y):
return x - y
f = lambda x, y, func: func(x,y)
>>> f(2, 4, div)
0.5
>>> f(2, 4, add)
6
>>> f(2, 4, sub)
-2
Lambda functions are often used in places where you need to use a simple function for a short period of time, but you don't want to define a full function using the def
keyword. They can be used, for example, as the function argument for higher-order functions like map
, filter
, and reduce
.