Python Nested Lambda Function (With Examples)

Python nested lambda function: In this tutorial, we will learn about the nested lambda function, its syntax, working, and examples. By IncludeHelp Last updated : December 30, 2023

In Python programming language, an anonymous function i.e., a function without a name and lambda keyword is known as the Lambda function. A normal function is defined by the def keyword and with a function name, while a lambda function is defined by the lambda keyword and without a function name.

Python Nested Lambda Function

When a lambda function is used inside another lambda function then it is called Nested Lambda Function.

Execution Behaviour

The execution behavior of the nested lambda function is - the inner lambda function creates a function when the outer lambda function is called. The outer lambda function returns this function. This function is then called with the given argument.

Syntax

Below is the syntax to declare a nested lambda function:

lambda parameterlist : lambda parameterlist : expression

Consider the below examples,

Nested Lambda Function (Example 1)

# Python program to demonstrate the use of 
# nested lambda functions
    
func = lambda x = 1, y = 2:lambda z: x +y+z
  
objF = func()

print(objF(1))
print(objF(2))
print(objF(3))
print(objF(4))

Output

4
5
6
7

Explanation

In the above code, we created an object objF of func, and called it 4 times with different values 1, 2, 3, and 4. When objF is called with the provided value – the nested lambda function will take the value of x and y from the first lambda function (the values are 1 and 2) and the value of z will be called the object's parameter that is 1 in first the case (print(objF(1))).

Nested Lambda Function (Example 2)

# Python program to demonstrate the use of 
# nested lambda functions
  
# Calculate cube
cube = lambda a: a**3 

# Calculate product with cube
product = lambda f, n: lambda a: f(a)*n

result = product(cube, 10)(5)
print(result)

result = product(cube, 10)(2)
print(result)

Output

1250
80

Explanation

For case 1 (product(cube, 10)(5)): When the product function is called cube function gets bound to f and 10 gets bound to n which then returns a function which is bound to the product which when called with 5, a is assigned this and cube is called, which returns 125 and then it is multiplied with n which is 10. Thus, the final result will be 1250.

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.