In the following article we will look at what is
Python anonymous functions。 Learn about Python's anonymous functions, and
Benefits of Python anonymous functions。 Well, don't say much nonsense, let's get into the next article.
anonymous functions
Python uses lambda to create anonymous functions.
Lambda is just an expression, and the function body is much simpler than def.
The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.
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:
>>> list (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<function <lambda> at 0x101c6ef28>>>> F (5) 25