Python Anonymous Functions
Python Anonymous Functions
In this tutorial, we will learn about Python anonymous functions. These functions are called anonymous because they do not follow the standard Python function definition by using the def keyword and are not bound to a name.
Anonymous Functions
These functions are also known as Lamda functions. These are created using the keyword lambda at runtime. The general syntax of the lambda function is as follows:
lambda arguments: expression
The lambda function can take multiple arguments and return a single value computed through the lambda expression.
Note that the lambda function cannot contain multiple lines of coding statements. No additional code statements can be written in the lambda function; it has only a local namespace, meaning it can use only those variables passed as arguments.
For example:
lambda arg1,arg2,…..argn: expression
lambda a,b:a + b
Example
A simple example that illustrates the anonymous function is as follows:
# This program illustrates an anonymous function
# Python language Tutorials - www.TestingDocs.com
add = lambda a, b: a + b
result = add(45, 15)
print('Sum of 45 and 15 ={0}'.format(result))
The Python program computes the addition of two numbers by using an anonymous function. We can see that the variable add is used as a function name while calling and passing the argument values to the anonymous function. The lambda expression that performs the addition of the arguments is computed, and the result is assigned to the variable.
—
Python Tutorials
Python Tutorial on this website can be found at: