Signup/Sign In

Lambda function in Python

Posted in Programming   LAST UPDATED: NOVEMBER 16, 2021

    Lambda functions in python, also known as anonymous functions are those which don't possess a name. In general, while declaring or defining a function, we use the def keyword along with a name for the function. But in the case of lambda functions, we use the keyword lambda (hence the name lambda function) and then define the function.

    Syntax of lambda function

    Following is the syntax of the lambda function.

    lambda arguments : expression(result of this is returned)

    Characteristics of lambda functions:

    1. It can have multiple arguments (there is no limit to the number of arguments) that can be passed to a lambda function.

    2. It can have one and only one expression.

    3. If there is a need for function objects in the code, the lambda function can be used there.

    4. It could be passed as an argument itself to built-in/customized higher-order functions.

    Now let's see how a lambda function varies with respect to regular function with the help of an example.

    The below example tries to square a number. As can be seen, the lambda function doesn't have a return statement and the expression itself is computed and returned as output. While using a regular function to square a number, it needs to be defined, arguments have to be passed and a return value has to be specified. It can be clearly seen that lambda functions are simpler and concise in comparison to regular functions.

    # normal function
    def square(a): 
        return a*a; 
      
    # lambda function
    anon_fun = lambda a: a*a 
    
    print("Using lambda function:")
    print(anon_fun(12)) 
    
    print("Using regular function:")  
    print(square(12))

    Output:

    Using lambda function:
    144
    Using regular function:
    144

    Why should I use lambda function when I could simply use a normal function?

    Well, methods are used to modularize code and make it more readable. What if the method is needed just for one single computation or for a short period of time? This is when lambda functions come handy since they don't need to be specifically defined with a name and there is no need to mention the return type as well.

    Sometimes, lambda functions are passed as arguments to other high-level functions as well. In general, lambda functions are used in conjunction with built-in functions like filter() function, map() function, and reduce() function.


    1. Using lambda function with the filter function

    The filter function in python takes the lambda function as one of the arguments which will act as the function acting as the filter criteria. The filter function is called with all parameters provided to it, post which, it returns the resultant data structure. As the name suggests, it is used to filter out unnecessary or invalid values from a data structure, in general, a list.

    Time for an example:

    The below code filters out values that are divisible by 5 only from a given list. It then returns the result in the form of a list.

    my_list = [1, 4, 5.0, 120.0, 4, 9, 56, 11, 3, 72]
    filtered_list = list(filter(lambda a: (a%5 == 0), my_list))
    print(filtered_list)

    Output:

    [5.0, 120.0]


    2. Using lambda function with map method

    The map function is a built-in method in Python that takes a function and a list as its arguments. The resultant list is a new one that contains data that has been modified by calling the lambda function on its values. For example if we have to double the integer values stored in a list, we can do so using the map function or we have to add a particular number to all the data elements of any data structure, etc.

    Time for an example:

    In the below example, the lambda function checks if a value in the list is divisible by 5 or not. If it is divisible, a True value is returned. Otherwise, it evaluates to False.

    my_list = [1, 4, 5.0, 120.0, 4, 9, 56, 11, 3, 72]
    filtered_list = list(map(lambda a: (a%5 == 0), my_list))
    print(filtered_list)

    Output:

    [False, False, True, True, False, False, False, False, False, False]


    3. Using lambda function with reduce method

    Similar to the map method, the built-in reduce method also takes in a lambda function and a list as arguments. A repetitive operation is performed on the data elements present inside the list. The reduce method is a part of the functools module.

    Time for an example:

    The below example defines a lambda function that subtracts data elements present in a list.

    from functools import reduce
    
    my_list = [1, 4, 5.0, 120.0, 4, 9, 56, 11, 3, 72]
    filtered_list = reduce((lambda a, b: a-b) , my_list)
    print(filtered_list)

    Output:

    -283.0


    Conclusion:

    In this post, we saw what a lambda/anonymous function is, its syntax, its characteristics and how it can be used. Don't forget to execute the code in your own IDE and understand the results.

    You may also like:

    Published by: SmritiSatyan
    Tags:PythonPython LambdaAnonymous Functions
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS