A lambda function basis
The 1.LAMBDA function is an anonymous function, that is, there is no specific function name, and the function created by the DEF function has a function name.
>>> def foo (): Return ' Test ' #命名为foo的函数
>>> Lambda: ' Test ' #用lambda关键字创建, equivalent to the function above
<function <lambda> at 0x0000000002fc18c8>
The above lambda function creates a function object that is not saved or called, and is retracted at any time, following which we save and invoke:
>>> a=lambda: ' Test '
>>> A ()
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 a return value to the right of the colon. A lambda statement is actually built as a function object.
2. No parameters and parameter conditions
No argument is not preceded by a colon, as the above example
The case with parameters:
>>> def add (x, y): Return x+y
>>> Add2=lambda X,y:x+y
>>> Add (2,2)
4
>>> Add2 (2,2)
4
>>> def sum1 (x,y=10): Return x+y
>>> Sum2=lambda X,y=10:x+y
>>> sum1 (2)
12
>>> sum2 (2)
12
>>> sum2 (1,100)
101
Three, the difference
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.
A lambda expression acts as a function sketch. Allows the definition of a function to be embedded within the code.
Lambda can also appear in the DEF function:
>>> def Action (x):
Return Lambda Y:x+y
>>> A=action (2)
>>> A (22)
24
This defines an action function that returns a lambda expression. Where the lambda expression obtains the value of the variable name x for the upper def Scope.
A is the return value of the action function, a (22), which is the lambda expression called the action return.
Python--lambda