When we pass in a function, there are times when we don't need to explicitly define a function, and it's easier to pass in an anonymous function directly.
In Python, there is a limited amount of support for anonymous functions. As an example of the map () function, when calculating f (x) =x2, in addition to defining an F (x) function, you can also pass in the anonymous function directly:
>>> Map (Lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]
The comparison shows that the anonymous function lambda x:x * x is actually:
def f (x): return x * x
The keyword lambda represents an anonymous function, and the x preceding the colon represents the function parameter.
There is a limit to the anonymous function, that is, there can be only one expression, without writing return, the return value is the result of that expression.
There is a benefit to using anonymous functions because the function does not have a name and does not have to worry about function name collisions. 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 invoke the function:
>>> f = Lambda x:x * x>>> f
at
0x10453d7d0>>>> F
(5)
Similarly, anonymous functions can be returned as return values, such as:
def build (x, y): return lambda:x * x + y * y
Summary
Python's support for anonymous functions is limited, and anonymous functions can be used only in some simple cases.