python Lambda
When we use functions, sometimes we do not need to show the definition of a function, we can use the anonymous function more convenient, in Python to the anonymous function also provides support.
For example, when we want to calculate the sum of two numbers, A and B, that is f (b) = a + We can do it in two ways, the first is to show the definition of a function f (x, y) and then pass the parameters in to get the result. The second way is to use anonymous functions.
f = Lambda x,y:x+y >>>f (3)
The anonymous function lambda x,y:x+y is actually:
def f (x, y): return x + y
In Python, the keyword lambda represents an anonymous function, and the x, Y representation of the colon precedes the arguments of the function, and the syntax of the anonymous function is:
Lambda [arg1[,arg2,arg3....argn]]:expression
In a lambda statement, the colon is preceded by a parameter, which can have multiple, separated by commas, and the result of the expression to the right of the colon as the return value of the anonymous function.
One limitation of an anonymous function is that there can be only one expression, and the return value of the anonymous function is the result of the expression without writing return. 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
The anonymous function can also be returned as a function return value, such as:
def build (x, y): return lambda:x + y
Thank you for reading, hope to help everyone, thank you for the support of this site!