Lambda wrapper function
In Python, anonymous function means that a function is without a name. As we already know that def
keyword is used to define the normal functions and the lambda
keyword is used to create anonymous functions. This function can have any number of arguments but only one expression, which is evaluated and returned. Lambda function can also have another function as an argument. The below example shows a basic lambda function where another lambda function is passed as an argument.
# Defining lambda function square = lambda x:x * x # Defining lambda function # and passing function as an argument cube = lambda func:func * * 3 print ( "square of 2 is :" + str (square( 2 ))) print ( "\nThe cube of " + str (square( 2 )) + " is " + str (cube(square( 2 )))) |
Output:
square of 2 is :4 The cube of 4 is 64
Passing function as an argument in Python
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects. In the example below, a function is assigned to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell.
# Python program to illustrate functions # can be treated as objects def shout(text): return text.upper() print (shout( 'Hello' )) yell = shout print (yell( 'Hello' )) |
Output:
HELLO HELLO