Anonymous Function


 Anonymous Function

       These functions are called anonymous because they are not declared in the standard manner by using the def keyword. The anonymous functions are the functions created using a lambda keyword. Lambda expression is used to create the anonymous function.

Lambda functions can take any number of arguments but return only one value in the form of an expression. They can not contain commands or multiple expression.

An anonymous function can not be a direct call to print because lambda requires an expression.


Syntax

lambda arguments: expressions

Syntax of lambda function contains only a single statement

Example 1 :

# a is an argument and a+10 is an expression which got evaluated and returned

x=lambda a: a+10

print(x(5))

Output

15

In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument and a+10 is an expression. The given expression gets evaluated and returned the result. 

Example 2 : 

# a and b are the arguments and a*b is the expression which gets evaluated and returned. 

x=lambda a,b:a*b

print(x(5,6))

Output

30

Example 3 :

A lambda function that sums argument a, b and c and print the result.

# a,b and c are the arguments and a+b+c is the expression which gets evaluated and returned.

x=lambda a,b,c:a+b+c

print(x(5,6,7))

Output

18














No comments:

Post a Comment