Python Programming – Python Anonymous Functions
Python supports the development of an additional type of function definition known as an anonymous function. These functions are termed anonymous because they do not follow the standard method by using the def keyword and anonymous functions are not bound to a name. These are created at runtime, using the construct known as lambda. The syntax of lambda is as follows:
|lambda arg1, arg2,…, argn: expression|
Characteristics of Lambda Form (Anonymous Function)
• lambda form can take multiple arguments as shown in the syntax and returns only one value computed through the expression.
• It does not contain multiple lines of statement blocks as in standard Python functions.
• Since, an expression is required in lambda form, the direct call to print() function can not be made in lambda form of anonymous function.
• As no additional statements can be written in lambda form, it has only a local namespace that means it can use only those variables that are passed as arguments to it or which are in the global scope.
• The lambda form (anonymous functions) can not be considered as C/C++ inline functions, as they contain only a single line of the statement. The concept of the Python anonymous function is entirely different from the C/C++ inline function and can be used with typical functional concepts.
The programming example illustrating the use of the lambda function is given in Code: 6.10. This program computes the product of two numbers, by using an anonymous function. We see that the variable product is used as a function name while calling and passing the argument values to the lambda (anonymous function). Lambda is just a single line statement, which performs the intended task and the result is assigned to the product variable. The function print() prints the value of the computed product using the lambda function. A similar program to compute the product of two numbers without using the lambda anonymous function is presented in Code: 6.11.
- Python Programming – Top-Down Approach Of Problem Solving
- Python Programming – Python Functions
- Using Exponents in Python | How to Calculate Exponents using Python? | Python math.exp() Method
Code: 6.10. Illustration of anonymous functions (lambda form).
|# This program illustrates the concept of lambda form (anonymous function)
#anonymous function definition
#product can be called as function as follows
Code: 6.11. Illustration of computation of product without using anonymous functions.
|# This program illustrates the Product of two numbers
def product(a, b):
# function call of product()