When we pass in a function, there are times when we do not need to define the function explicitly, and it is more convenient to pass in the anonymous function directly.
In Python, you provide limited support for anonymous functions. Or take the map () function as an example, when you compute f (x) =x2, you can also pass in the anonymous function directly, in addition to the function that defines an F (x):
>>> Map (Lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
As you can see from the comparison, the anonymous function lambda x:x * x is actually:
The keyword lambda represents an anonymous function, and the x in front of the colon represents the function argument.
There is a limit to the anonymous function, that is, there can be only one expression, and the return value is the result of the expression without a write-back.
There is a benefit to using an anonymous function because a function has no name and does not have to worry about a function name conflict. In addition, the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to call the function:
>>> f = Lambda x:x * x
>>> F
<function <lambda> at 0x10453d7d0>
>>> F ( 5) #
25
Similarly, anonymous functions can be returned as return values, such as:
def build (x, y): Return
lambda:x * x + y * y
Summary
Python has limited support for anonymous functions, and there are only a few simple cases where anonymous functions can be used.