Skip to content
Home » Programming » Anonymous/Lambda Functions in Python

Anonymous/Lambda Functions in Python

anonymous/lambda-functions-in-python

In this post, we will clarify the concept of Anonymous/Lambda Functions in Python. All the functions we have had defined a name that they can be referenced by, such as greeter or get_integer_input etc. This means that we can reference and reuse these functions as many times as we like.

However, in some cases we want to create a function and use it only once; giving it a name for this one time can pollute the namespace of the program (i.e. there are lots of names around) and also means that someone might call it when we don’t expect them to.

Python therefore another option when defining a function; it is possible to define an anonymous function. An anonymous function is one that does not have a name; and used at the point that it is declared.

Anonymous functions are defined using the keyword lambda and for this reason they are also known as lambda functions.

Also Read: Function Parameters in Python

Declaration of Anonymous/Lambda Functions in Python

The syntax used to define an anonymous function is:

lambda arguments : expression

Anonymous functions can have any number of arguments but only one expression (that is a statement that returns a value) as their body. The expression is executed, and the value generated from it is returned as the result of the function.

As an example, let us define an anonymous/lambda functions in Python that will square a number.

double = lambda i : i * i

In this example, the lambda definition indicates that there is one parameter to the anonymous function ('i') and that the body of the function is defined after the colon ':' which multiplies i*i; the value of which is returned as the result of the function.

The whole anonymous function is then stored into a variable called double.

We can store the anonymous function into the variable as all functions are instances of the class function can be referenced in this way (we just haven’t done this so far).

To invoke the function, we can access the reference to the function held in the variable double. And then use the round brackets to cause the function to be executed, passing in any values to be used for the parameters.

print (double(10))

The output is 100 for above code snippet. Other examples of lambda/anonymous functions are below (illustrating that an anonymous function can take any number of arguments).

func0 = lambda: print ('no args')
func1 = lambda x: x * x
func2 = lambda x, y: x * y
func3 = lambda x, y, z: x + y + z
func0 ()
print (func1(4))
print (func2(3,4))
print (func3(2, 3, 4))

As a result, the output from this code snippet is

no args
16
12
9

Leave a Reply

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