Nested lambda Python function | Example code

A Python if lambda function inside another lambda function is called a nested lambda function. We can create another lambda function inside another lambda function.

Note: the lambda keyword is used to create anonymous functions.

Python Nested lambda function example

Simple example codes an outer and an inner lambda function. When you call the outer lambda, that time the inner lambda function is created. The outer lambda will return the called function.

Adding two numbers using Nested lambda Python functions:

add = lambda a=20: lambda b: a + b
x = add()

print(type(x))
print(x(50))

Output:

Nested lambda Python function

Another example

sqr = lambda x: x ** 2
prod = lambda f, n: lambda x: f(x) * n

ans = prod(sqr, 2)(10)
print(ans)

Output: 200

Do comment if you have any doubts and suggestions on this Python Lambda tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.