# What Is Nested Lambda Function? What Are Its Characteristics Give an Example?

4K The lambda function was initially introduced in the Python programming language because of the demand from LISP programmers. The term lambda originates from the Lambda Calculus, a form of mathematical calculus invented by Alonzo Church.

If the mention of Calculus has scared you, relax! You don’t have to master Calculus for using lambda functions. Lambda expressions are simple, concise and easy-to-understand – even a newbie can get the lambda syntax easily.

### Syntax

Lambda functions are one-liner functions. Every lambda function you define in python has three essentials – the keyword lambda, arguments and the expression. Here is the syntax of how we define a lambda function in python:

lambda arguments: expression
• Keyword: lambda
• Arguments: The user can define the number of arguments separated by a comma
• Expression: The expression is an arithmetic expression that uses the arguments defined by the user

## What Is a Lambda Function?

A lambda function is an anonymous function, i.e., a function without a name. It allows writing functions without naming them. Unlike the regular way of defining python functions, where we use the keyword def, we use the lambda keyword to define a lambda function.

# a function in python defined using the keyword – lambda
lambda a, b: a + b

is similar to writing a regular function in python,

# a function in python defined using the keyword – def
def sum(a, b):
return a + b

### Adding two numbers using Python lambda functions:

sum = lambda a, b: a + b
print("Result = ", sum(6,4))

Output:

Result = 10

Characteristics of Lambda functions in Python:

• Lambda functions can take multiple arguments but return just one value in the form of an expression.
• The lambda functions are throw-away functions, i.e., they are required where they have been created, and called anywhere in a function when required.
• Syntactically, they are a one-line version of a function and hence cannot contain multiple-line expressions.
• Lambda expressions can be passed as arguments to other functions.
• Lambda functions do not have an explicit return statement, but always contain an expression that is executed and returned.

Attention: You can use lambda functions wherever there is a need for function objects. However, they cannot access variables other than those present in their parameter list. Also, global variables cannot be accessed using the lambda function.

## What is a nested Lambda Function?

A lambda function inside a lambda function is called a nested lambda function. Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function. When the outer lambda is called, the inner lambda creates a function. The outer lambda then returns the called function.

Here is a small code to illustrate the nested lambda function:

Adding two numbers using Python lambda functions:

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

Output:

50

Here is a step-by-step explanation of the above code.

• Step-1: Define an outer lambda function (lambda a =10) & an inner lambda function (lambda b: a + b)
• Step-2: Assign both the lambda functions in a variable name sum.
• Step-3: Call the outer lambda function, and assign it to a variable x
• Step-4: Print x by assigning a value.

The assigned value of 30 is added up with the outer lambda function and finally, sum=50 is displayed in the output.

## Where Are Nested Lambda Functions Useful?

Nested lambda functions are significant when there is a need for function objects. Nesting allows hiding the mechanics of iteration operations, especially when working on complex projects. Nested lambdas can be easily embedded in places where def functions are restricted. Syntactically, they are useful in places where python wouldn’t allow a function to be defined using a regular def expression. Besides, nested lambda statements are also used along with sort methods to arrange the list elements in a sequence.

• Attention: With nested lambdas, recursion can occur and may also result in a runtime error.
RuntimeError: maximum recursion depth exceeded error

## How to Use Nested Lambda with the Sort Method

In general, sort() in python has two parameters, key, and reverse. The key value is None, and the reverse value is False, by default. Using the lambda function in the sort method, the key extends its capabilities and becomes more versatile. Here is a simple code to make you understand the importance of the lambda function with the sort method.

Sorting without using lambda function:

check_list = [[4, "Cherry"], [3, "Banana"], [1, "Apple"], [2, "Dragon Fruit"]]
check_list.sort()
print(check_list)

Output:

[[1, 'Apple'], [2, 'Dragon Fruit'], [3, 'Banana'], [4, 'Cherry']]

Look at both the codes carefully. The inner list doesn’t get sorted using the regular sort() method but gets sorted using the lambda functions in alphabetical order. Therefore, the lambda function is of the utmost importance when there is a need to sort the inner list sequentially in a pre-defined list.

Lambda functions are also used with python in-built functions like filter(), map(), and reduce(). Let’s have a look at each in detail:

## Use of Filter Function with lambda – filter ()

The filter () function in Python is an excellent way of filtering out all the elements of a sequence for which the function is True or False. The function includes only those values that satisfy the result and thus constructs a new list from those elements of the list for which the function returns True.

Here is a small code that returns the list of even numbers from an input list:

# Python code to illustrate filter() with lambda()
# Finding the even numbers from a given list
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
result = list(filter(lambda x: (x%2 ==0), li))
print(result)

Output:

[2, 4, 6, 8, 10, 12, 14]

From the output of the above program, we see the output returning only the true values. Only those values in the range that are even numbers i.e., divisible by 2, are included in the new list, and the rest are explicitly removed.

• Attention Please: If the sequence is a string, tuple, or Unicode, the output will be the respective same type, otherwise, the result is always a list.

### Use of Map Function with lambda – map()

The map() function in Python applies a unary function to each element in the list. After applying the specified function for each item in the list, the map() function returns the new list. The function calls each item in the sequence and returns a list of return values containing the results, in the same order.

Here is a small code that returns the list of cubes from an input list:

# Python code to illustrate map() with lambda()
# Cubing the list of numbers from a given list
nums= [1, 3, 5, 6, 4, 2]
result = list(map(lambda x: x**3, nums))
print(result)

Output:

[1, 27, 125, 216, 64, 8]

From the output of the above program, we can see that all the elements have been evaluated for each of the elements in the list. The corresponding cubes of all the elements in the list are added to the new list sequentially.

• Attention Please: Map() function also allows to pass more than one sequence if required. Just keep in mind two things when passing multiple sequences. Firstly, the number of arguments must be identical to the number of sequences. Secondly, each argument must be called from the corresponding item from each sequence.

### Use of Reduce Function with lambda – reduce()

The reduce() function combines the sequence elements using a binary function. It returns a single value generated by calling the function on the first two elements in the sequence. Once the two have been called, the result then gets added to the next item, and so on. The process continues until all the elements in the sequence get evaluated.

Pro-tip: Don’t forget to import reduce from the functools module.

Here is a small code that returns the list of the sum from an input list:

# Python code showing the use of reduce() with lambda()
# Finding the sum from a given list
lis = [1, 2, 3, 4, 5]
result = reduce ((lambda a, b: a + b), lis)
print(result)

Output:

15

The result of the first-two elements gets added to the next element. Here is what goes behind the scene à ((((1+2) + 3) + 4) + 5) = 15. The process is continued till the last element of the sequence is reached.

• Attention Please: If there is a single-value sequence, then the value of the sequence is returned. However, an exception is raised in an empty list.

## How to Test Lambda Functions

Lambda functions, no matter how simple they sound, also need to be tested at times. Testing a python lambda function is the same as testing a regular function. Unittest and doctest – python standard libraries are used to test lambda functions.

## Python Lambda Functions

Lambda functions in python are an effective way to define functions anonymously. The lambda functions being executed and returned in a single-line add a significant advantage with throw-away functions. However, lambda functions are not recommended if the expressions become complicated to read or interpret. If it is strenuous to get all the logic inside lambdas, use a def instead. ### Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.