What is lambda function in Python?

The anonymous function in python is a function that is defined without a name. The normal functions are defined using a keyword “def”, whereas, the anonymous functions are defined using the lambda function. The anonymous functions are also called as lambda functions.

A lambda function in Python is a small anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression, which is evaluated and returned. Lambda functions are commonly used when you need a simple function for a short period of time and don’t want to define a separate named function using the def keyword.

For example:

python
# Defining a lambda function to calculate the square of a number
square = lambda x: x * x

# Using the lambda function
print(square(5)) # Output: 25

Lambda functions can be used anywhere a function is required, such as within higher-order functions like map(), filter(), and reduce(), or as arguments to functions that expect a function object. However, lambda functions are limited to a single expression and cannot contain statements or multiple expressions.