In the following article, let’s learn about what python anonymous function is. Learn about python anonymous functions and the benefits of python anonymous functions. Okay, without further ado, let’s get started with 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 lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
Although the lambda function seems to only be able to write one line, it is not equivalent to the inline function of C or C. The purpose of the latter is to not occupy the stack memory when calling a small function and thus increase the operating efficiency.
When we pass in a function, sometimes there is no need to explicitly define the function. It is more convenient to pass in the anonymous function directly.
In Python, there is limited support for anonymous functions. Still taking the map() function as an example, when calculating f(x)=x2, in addition to defining a function of f(x), you can also directly pass in an anonymous function:
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))[1, 4, 9, 16, 25, 36, 49, 64, 81]
As can be seen from comparison, Anonymous function lambda x: x * x is actually:
def f(x): return x * x
The keyword lambda represents an anonymous function, and the x before the colon represents the function parameter.
Anonymous functions have a limitation, that is, they can only have one expression. There is no need to write return. The return value is the result of the expression.
Using anonymous functionshas the advantage, because the function has no name, so you don’t have to worry about function name conflicts. In addition, the anonymous function is also a function object. You can also 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 0x101c6ef28> >>> f(5)25
The above is all the content described in this article. This article mainly introduces I have knowledge about python anonymous functions, I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
>
The above is the detailed content of Python anonymous function definition and example analysis. For more information, please follow other related articles on the PHP Chinese website!