Python LambdaIn python, lambda is used to create anonymous functions. The method created with Def is named. Apart from the method names on the surface, what are the differences between Python Lambda and def?
1. Python Lambda creates a function object, but does not assign this function object to an identifier. Def assigns the function object to a variable.
2. Python Lambda is just an expression, while def is a statement.
The following is a simplified Python Lambda format.
Lambda X: Print x
If you use Python Lambda in Python list parsing, it doesn't make much sense, because Python Lambda creates a function object, but it is discarded immediately, because you didn't use its return value, that is, the function object. Lambda is just an expression that can be directly used as a member of the python list or Python dictionary, for example:
Info = [Lambda A: A ** 3, Lambda B: B ** 3]
There is no way to directly replace it with the def statement. Because def is a statement, not an expression that cannot be nested in it, lambda expressions can only have one expression after. That is to say, in def, return can be returned or placed behind lambda. return cannot be used or defined behind Python lambda. Therefore, statements such as if, for, or print cannot be used in Lambda. Lambda is generally only used to define simple functions.
Here are some examples of Python lambda.
1. For a single parameter:
G = Lambda X: x * 2
Print G (3)
The result is 6.
For more than 2 parameters:
M = Lambda X, Y, Z: (x-y) * z
Print M (3, 1, 2)
Result 4
Nothing to writeProgramWhen using Python lambda, you will be familiar with it ..
OriginalArticlePlease indicate Reprinted from Old Wang python, this article address: http://www.cnpythoner.com/post/97.html
Author: Lao Wang @ Python tutorial
Old Wang Python provides Python-related Django tutorials and Python downloads!