Anonymous / Lambda Function

Anonymous / Lambda Function

In Python, anonymous function is a function that is defined without a name.

  • Normal functions are defined using the 'def' keyword.
  • Anonymous functions are defined using the 'lambda' keyword.

  • Rules of Lambda Function

  • Lambda functions are small functions usually not more than a line.
  • The body of lambda functions consists of only one expression.
  • Lambda functions can have any number of arguments just like a normal function.
  • The result of the expression is the value when the lambda is applied to an argument.
  • There is no need for any return statement in lambda function.
  • It cannot contain commands or multiple expressions.
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

  • Syntax

        lambda [arg1,arg2,....,argn]:expression
    

    Example 1: Normal Function

    # Function to adds two numbers and returns the output
    def add(x,y):
        return x + y
    
    # Calling the Function
    add(10,25)
    
    Output:
    35
    

    Example 2: Lambda Function

    # Lambda Function to adds two numbers,returns the output and called through the variable
    sum = lambda x, y: x + y
    
    # call the lambda function
    print("Sum of two numbers : ",sum(10,25))   
    
    Output:
    Sum of two numbers :  35
    
  • Here we are using two arguments x and y.
  • Expression after colon is the body of the lambda function.
  • Lambda function has no name and is called through the variable it is assigned to.

  • (OR)

    # Lambda Function to adds two numbers and returns the output 
    (lambda x, y: x + y)(10,25)
    
    Output:
    35
    

    Lambda functions along with built-in functions

    Example 3 :

    # Program to filter out only the odd items from a list
    mylist = [1 , 5 , 15 , 22 , 58 , 98]
    oddlist = list(filter(lambda x: (x%2 != 0), mylist))
    print(oddlist)  
    
    Output:
    [1, 5, 15]
    

    Example 4:

    # Program to display cube of each item in a list using map()
    mylist2 = [1, 2, 3, 4, 5, 6, 7]
    cubelist = list(map(lambda x: x ** 3, mylist2))
    print(cubelist) 
    
    Output:
    [1, 8, 27, 64, 125, 216, 343]