This article mainly introduces the use of anonymous functions in Python. lambda is an important function in various modern programming languages. if you need it, you can refer to the following when we pass in functions, you do not need to explicitly define a function. it is more convenient to directly input an anonymous function.
In Python, anonymous functions are provided with limited support. Take the map () function as an example. when f (x) = x2 is calculated, in addition to defining an f (x) function, you can also directly input an anonymous function:
>>> map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])[1, 4, 9, 16, 25, 36, 49, 64, 81]
From the comparison, we can see that the anonymous function lambda x: x * x is actually:
def f(x): return x * x
The keyword lambda indicates an anonymous function, and the x before the colon indicates a function parameter.
There is a limit on anonymous functions, that is, there can be only one expression, and no return is required. The return value is the result of this expression.
There is a benefit to using an anonymous function because the function has no name and you don't have to worry about function name conflicts. In addition, an anonymous function is also a function object. you can assign an anonymous function to a variable and use the variable to call the function:
>>> f = lambda x: x * x>>> f
at 0x10453d7d0>>>> f(5)25
Likewise, anonymous functions can be returned as return values, for example:
def build(x, y): return lambda: x * x + y * y
Summary
Python has limited support for anonymous functions. anonymous functions can be used only in some simple cases.