For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

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

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

Published
30th Jan, 2024
Views
view count loader
Read it in
7 Mins
In this article
    What Is Nested Lambda Function? What Are Its Characteristics Give an Example?

    As a Python developer, I regularly work with lambda functions to write clean, concise code. Lambdas are anonymous functions that allow you to inline small bits of code without having to define an entire function. However, as my Python skills have grown, I've found myself using nesting lambdas more and more. While nested lambda function in Python may seem complicated at first, they allow you to chain together functions elegantly.

    In this article, I'll walk through what a nested lambda is, provide examples, discuss their usefulness, and when you may need one in Python. I'll also cover how to use nested lambdas with built-in functions like sort and filter. By the end, you'll have a solid grasp of this unique Python concept so you can utilise it in your own code.

    Nested lambda function in Python

    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
    x = add()
    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.

    Nested Lambda Function Example

    Here are two examples of using nested lambdas in Python:

    Example 1:

    This example multiples two numbers by using nested lambdas:

    multiplier = lambda x: (lambda y: x * y)  
    double = multiplier(2)
    print(double(15)) # Prints 30

    Here the outer lambda function python accepts x and returns another lambda, which accepts y and returns x * y. This allows us to specialise the multiplier lambda by baking in the first parameter.

    We call the outer lambda, pass in 2 which gets bound to x. This returns a specialised lambda that doubles its input. We pass 15 to this double lambda and it prints out 30.

    Example 2:

    This example sorts a list of strings by the last letter: 

    strings = ['cat', 'dog', 'armadillo']
    sorted_strings = sorted(strings, key=lambda word: (lambda x: x[-1])(word))  
    print(sorted_strings) # ['cat', 'armadillo', 'dog']

    Here the key function is a lambda that accepts a word. This word gets passed into another lambda, which returns the last letter of that word. This returns the last letter for each word, which gets used by sorted() to sort the list of strings.

    The nested lambda allows us to elegantly handle sorting by a computed key in one line.

    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

    Nested Lambda Functions

    When is Nested Lambda Needed in Python?

    While Python supports defining multi-line functions, at times I find myself in situations where using a nested lambda drastically simplifies my code.

    One case is when I'm iterating through a collection and calling functions that require other functions. For example, needing to sort a list of dicts based on a key function that extracts a nested value. By using lambdas, I can compactly define these operations in place instead of declaring one-off functions. Creating a concise and powerful solution with a Lambda function in Python is easy.

    Nested lambda functions in python are also useful when mapping or filtering data structures. I can cleanly pipe data through each transformation without temporary variables or function calls cluttering up my code. Lambda nested list python allows cleanly chaining transformations when mapping across lists, nesting functions together elegantly without unnecessary temporary variables cluttering code.

    Another case is when I'm using Python interactively or writing a quick script. Defining formal functions interrupts the flow whereas a nested lambda function in python keeps the code scanning linearly. Even in scripts, I may just want a throwaway function rather than dedicating lines for a function I won't reuse.

    Ultimately Python nested lambda allows you to minimise repetitive code when you need to pass in callable logic. The lambdas act as clean, self-contained units that can be composed together like Lego blocks. While they may seem confusingly compact at first, when used judiciously, they wonderfully simplify your code.

    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.

    How to Test Lambda Functions?

    Testing lambda functions can be challenging since they have no name, and we can't directly import and call them. Here are some strategies for testing lambdas: 

    • Wrap logic in named function first: Defining the function longhand allows testing it directly. Then convert to a lambda. 
    • Assign to variable: Calling my_func = lambda x: x + 1 lets you test by passing values to my_func. 
    • Unit test parent functions: If the lambda is used as a parameter, unit test that parent function with different inputs. 
    • Print input & outputs: Use print statements in the lambda body and params to debug values. 
    • Simulate data pipelines: Pass mock data sets into chained lambdas and print outputs at each stage. 
    • Catch exceptions: Try/catch blocks around lambdas can reveal runtime issues. 
    • Libraries: Use of Unittest and doctest libraries to test lambda functions. 

    While it takes some creativity, by utilising these approaches you can test and validate nested lambdas. The key is to stepwise unit test encapsulating logic until the lambda performs as expected. 

    Conclusion

    Through hard-won experience, I've found nested lambdas indispensable for streamlining Python code. Chaining these anonymous functions creates elegant pipelines for data transformations that minimise clutter. Though simple alone, combined they enable complex logic concisely. I often utilise them interactively when needing quick throwaway functions that won't break my flow. While opaque initially, methodically testing stages validates nested lambdas work right. Once their artistry clicks for you too, I think you’ll find lambda composition a cherished tool for functional artistry, allowing you to tame code with surprising power. Give them a test drive - you may just gain a secret weapon! 

    Profile

    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.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon