In Python, a nested lambda function is a lambda function that is defined inside another lambda function. The outer lambda function serves as a wrapper for the inner lambda function and can pass arguments to it.
The syntax for defining a nested lambda function is:
lambda argument1: lambda argument2: expression
Here, argument1
is the input to the outer lambda function and argument2
is the input to the inner lambda function. The expression
is the operation performed by the inner lambda function?
For example, consider a nested lambda function that takes two arguments and returns their product:
multiply = lambda x: lambda y: x * y print(multiply(2)(3)) # Output: 6
In the above example, the outer lambda function lambda x:
takes an argument x
and returns an inner lambda function lambda y:
. The inner lambda function takes an argument y
and returns the product of x
and y
.
You can also pass arguments to the outer and inner lambda functions separately. Here is an example that takes three arguments and returns their sum:
sum_three = lambda x: lambda y: lambda z: x + y + z print(sum_three(1)(2)(3)) # Output: 6
In the above example, the outer lambda function lambda x:
takes an argument x
and returns an inner lambda function lambda y:
. The second inner lambda function lambda z:
takes an argument z
and returns the sum of x
, y
, and z
.