Python lambda function can allow us to create an anonymous function, in this tutorial, we will introduce how to use lambda correctly for python beginners.
As to a python function, there are three key points::
Function parameters: these parameters will be passed into function.
Function body: the main process of function.
Return value: the value of function will return.
As to a normal python function, function name is also a key point.
However, we can use python lambda function to create an anonymous function, which means this function does not have a function name.
Lambda is defined as:
lambda arguments : expression
Here
arguments are function parameters will be passed into a function.
expression is the function body.
The result of expression is the return value of a function.
For example:
x = lambda a, b: a *b y = x(4,5)
Where
a, b is the parameters.
a * b is the function body.
The result of a * b is the return value.
x is an anonymous function.
print(type(x))
The type of x is: <class ‘function’>
The result of:
y = x(4,5)
is 20.
This lambda expression is equivalent to
def compute(a, b): return a * b
compute is a normal function, compute is the name of a function.