Python Lambda Function

Posted on Oct 31, 2019


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():

1
2
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.

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

Expected Output:

36
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:

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

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


Other Tutorials (Sponsors)