First, Lambda uses syntax:
The keyword lambda
represents an anonymous function, a function argument preceded by a colon, and x
only one expression after the colon, without writing return
, and the return value is the result of the expression.
1 >>> list (map (lambda x:x * x, [1, 2, 3, 4, 5]))2 [1, 4, 9, 16, 25]
parameter-free lambda expression:
1 Lambda : 2 * 22 >>> f ()3 4
Second, the anonymous function is a function object
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:
1 Lambda x:x * x2 >>> F3 <function <lambda> at 0x1014aea60>4 >>> F (5)5 25
You can also use anonymous functions as return values:
1 def build (x, y): 2 ... return Lambda : x * x + y * y34 >>> f = Build (1, 2)5 >>> F ()6 5
Python anonymous function lambda