Why do we need Lambda functions in Python ? | Explained with examples.

In this article we will discuss what is a lambda function in python and why they are required. Basically what are the use cases which makes use of lambda function must.

What is a lambda function ?

Lambda functions are also called Anonymous functions because they don’t have any name. Also they can be assigned to variables and passed to other functions as arguments.

Unlike other functions they are defined using ‘lambda’ keyword and syntax for their definition is as follows,

lambda args : expression

It accepts the arguments in args and returns the value evaluated by expression.

Let’s understand by an example,

Suppose we have a function that calculates the cube of a given number i.e.

# A function the returns the cube of a given number
def cube(num):
    return num*num*num

Now, suppose we need to call this function only one time in our code. So, instead of creating a separate function we can create a lambda function that does the same work i.e.

lambda x : x*x*x

While defining a lambda function we can assign this to a variable and call it using that variable i.e.

# Create a lambda function to calculate cube of a given number
# Assign back this lambda function to a variable.
cubeFunc = lambda x : x*x*x

# call the lambda function
print('Cube of 3 is : ', cubeFunc(3))

Output:

Cube of 3 is :  27

But wait, why would any one will create a lambda function ? As we said above the for one time tasks we can create lambda functions.
But if it’s one time task only, then we can write the code directly instead of creating any other function or lambda function like this,

x=3
print(x*x*x)

Then why we need lambda functions ? Let’s look deeper to understand the need,

Need of a lambda function

An important aspect of a lambda function is that it can be passed to other function as arguments. This is the main thing that drives a need of
lambda function. Let’s understand this aspect by an example,

Suppose we have a function that accepts two arguments, a list of elements and callback function i.e.

'''
This function accepts a list of elements & a callback function.
Then returns a new list by calling callback function on each element of
given list and storing it's result in new list. In the end returns the new list.
'''
def converter(listOfelems, callback):
    newList = list()
    # Iterate oover each element of list
    for elem in listOfelems:
        # call given function on each element & append result in new list
        newList.append(callback(elem))
    return newList

This function iterates over all the elements in list and calls the passed callback() function on each of the element. Also, stores the value returned by each call to callback() function to an another list.

So, this function is basically converting values in list to some other values in new list. But what’s the conversion logic ? Conversion logic is passed to this function as a callback function.
Let’s use this function to convert a list of numbers to their cube i.e.

# A function the returns the cube of a given number
def cube(num):
    return num*num*num

# List of numbers
listOfNum = [2,3,4,5,6,7]
print('Original list : ', listOfNum)

print('Converting numbers to their cube :')

# passing cube() as callback function
modList = converter(listOfNum, cube)
print('Modified list : ', modList)

Output:

Original list :  [2, 3, 4, 5, 6, 7]
Converting numbers to their cube :
Modified list :  [8, 27, 64, 125, 216, 343]

As we can see in output converter() returns a list of numbers which are basically cube of numbers passed in other list.

Important observation :

For calling converter() we need to pass a function as argument. Therefore we created a small cube() function. Now most probably this function will not be used by anywhere else. Also, if we are going to use converter() function again for some other conversions then we are again going to create some small functions, which will never be used again. So basically we are going to pollute our code.

Is there anyway to prevent this pollution of code with numerous one time used small functions ?
Yes, here comes the Lambda function in picture.

We can call the converter() function to convert the list of numbers to their cube by passing a lambda function in converter() as argument i.e.

# passing lambda function as callback function
modList = converter(listOfNum, lambda x : x*x*x)
print('Modified list : ', modList)

Output:

Modified list :  [8, 27, 64, 125, 216, 343]

So, basically instead of creating a separate function cube() we passed a lambda function to the converter() function.

Similarly we can call the converter() with another lambda function to convert the list of numbers to their square i.e.

# passing lambda function as callback function
modList = converter(listOfNum, lambda x : x*x)
print('Modified list : ', modList)

Output:

Modified list :  [4, 9, 16, 25, 36, 49]

Similarly we can call the converter() with another lambda function to convert the list of numbers from celsius to farhaneit i.e.

listOfNum = [35, 36, 37,38,40]

# passing lambda function as callback function
modList = converter(listOfNum, lambda x : (x*9)/5 + 32)
print('Modified list : ', modList)

Output:

Modified list :  [95.0, 96.8, 98.6, 100.4, 104.0]

Now by using lambda function we prevented the creation of 3 small ONE TIME functions here. So, this is how lambda function prevents the creation of small one time functions and shows it’s usefulness.

Passing multiple arguments in lambda functions

We can also create lambda functions that accepts multiple arguments i.e.

# Creating a lambda function with multiple arguments
multipier = lambda x, y, z: x * y * z
value = multipier(3, 4, 5)
print(value)

Output:

60

Complete example is as follows,

'''
This function accepts a list of elements & a callback function.
Then returns a new list by calling callback function on each element of
given list and storing it's result in new list. In the end returns the new list.
'''
def converter(listOfelems, callback):
    newList = list()
    # Iterate oover each element of list
    for elem in listOfelems:
        # call given function on each element & append result in new list
        newList.append(callback(elem))
    return newList

# A function the returns the cube of a given number
def cube(num):
    return num*num*num

def main():

    # Create a lambda function to calculate cube of a given number
    # Assign back this lambda function to a variable.
    cubeFunc = lambda x : x*x*x

    # call the lambda function
    print('Cube of 3 is : ', cubeFunc(3))

    print('*** Need to lambda functions ****')

    # List of numbers
    listOfNum = [2,3,4,5,6,7]
    print('Original list : ', listOfNum)

    print('Converting numbers to their cube using cube() function:')

    # passing cube() as callback function
    modList = converter(listOfNum, cube)
    print('Modified list : ', modList)

    print('*** Converting numbers to their cube using lambda function ***')

    # passing lambda function as callback function
    modList = converter(listOfNum, lambda x : x*x*x)
    print('Modified list : ', modList)

    print('*** Converting numbers to their square using lambda function ***')

    # passing lambda function as callback function
    modList = converter(listOfNum, lambda x : x*x)
    print('Modified list : ', modList)

    print('*** Converting numbers from celsius to fahrenheit using lambda function ***')

    listOfNum = [35, 36, 37,38,40]

    # passing lambda function as callback function
    modList = converter(listOfNum, lambda x : (x*9)/5 + 32)
    print('Modified list : ', modList)

    print('*** Passing multiple arguments to lambda functions ***')

    # Creating a lambda function with multiple arguments
    multipier = lambda x, y, z: x * y * z
    value = multipier(3, 4, 5)
    print(value)

if __name__ == '__main__':
    main()

Output:

Cube of 3 is :  27
*** Need to lambda functions ****
Original list :  [2, 3, 4, 5, 6, 7]
Converting numbers to their cube using cube() function:
Modified list :  [8, 27, 64, 125, 216, 343]
*** Converting numbers to their cube using lambda function ***
Modified list :  [8, 27, 64, 125, 216, 343]
*** Converting numbers to their square using lambda function ***
Modified list :  [4, 9, 16, 25, 36, 49]
*** Converting numbers from celsius to fahrenheit using lambda function ***
Modified list :  [95.0, 96.8, 98.6, 100.4, 104.0]
*** Passing multiple arguments to lambda functions ***
60

 

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top