In Python, a lambda function (also called an anonymous function) is a small, anonymous function that can be defined in a single line of code without a name. It is useful when we need a simple function that we don’t want to define explicitly using the def keyword.
The basic syntax for a lambda function in Python is:
lambda arguments: expression
Here, arguments refer to the input arguments for the function and expression is a single expression that gets evaluated and returned as the result of the function. The result of the expression is automatically returned by the lambda function, so there’s no need to use the return statement.
For example, the following code defines a lambda function that takes two arguments and returns their sum:
f = lambda x, y: x + y
We can then call the function f like any other function, passing in the required arguments:
result = f(3, 4)
print(result) # Output: 7
Lambda functions can be used in many contexts where a small, one-time-use function is needed, such as in the map(), filter(), and reduce() functions, or as a key function in the sorted() function.
Let see some more complex examples
Multiply two numbers:
multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result) # Output: 12
Note that in each of these examples, we define a lambda function on the fly and use it as needed, without assigning it a name. This is one of the key benefits of lambda functions, as they allow us to write concise and readable code without cluttering the namespace with unnecessary function names.
Here are some complex examples that demonstrate how lambda functions can be used in real-world scenarios:
Sorting a list of dictionaries based on a specific key