Lambda in Python

In Python, lambda is a single-line function with no name, also known as anonymous or lambda functions. A lambda function can have any number of arguments but only one expression. The result is returned after the expression is executed. This lambda function is not declared using the def keyword.

The basic syntax of a lambda function is as follows:

lambda arguments: expression

Here's a simple lambda function to add and return the value of two numbers:

add = lambda x, y : x + y
result = add(10, 20)

In this example, lambda x, y : x + y creates a lambda function that takes two arguments x and y and returns their sum. We then assign this lambda function to the variable add and use it to add 10 and 20, resulting in 30.

The output of the above code is as follows:


Here's an example of another lambda function that multiplies two numbers and returns the result:

product = lambda x, y : x * y
print(product(5, 10))

The output of the above code is as follows:


Why use Lambda Function?

A lambda function is useful when we are required to use an anonymous temporary function within another function.