Python Lambda Function

Updated on Jan 07, 2020

Python allows you to create anonymous function i.e function having no names using a facility called lambda function.

Lambda functions are small functions usually not more than a line. It can have any number of arguments just like a normal function. The body of lambda functions is very small and consists of only one expression. The result of the expression is the value when the lambda is applied to an argument. Also there is no need for any return statement in lambda function.

Let's take an example:

Consider a function multiply():

def multiply(x, y):
    return x * y

This function is too small, so let's convert it into a lambda function.

To create a lambda function first write keyword lambda followed by one of more arguments separated by comma (,), followed by colon a (:), followed by a single line expression.

r = lambda x, y: x * y
r(12, 3)   # call the lambda function

Expected Output:

r = lambda x, y: x * y
print(r(12, 3))   # call the lambda function

Here we are using two arguments x and y, expression after colon is the body of the lambda function. As you can see lambda function has no name and is called through the variable it is assigned to.

You don't need to assign lambda function to a variable.

(lambda x, y: x * y)(3,4)

Expected Output:

print( (lambda x, y: x * y)(3,4) )

Note that lambda function can't contain more than one expression.

Other Tutorials (Sponsors)