Absrtact: Do you not often encounter situations where you need to use a function that is very simple and is only used temporarily and does not want to pollute the namespace. If you often encounter this requirement, or see Lamda expressions in Python, this article will discuss LAMDA expressions with you.
1. What is a LAMDA expression
Python supports an interesting syntax that allows you to quickly define the smallest function of a single line. These functions, called Lambda, are borrowed from Lisp and can be used wherever a function is needed.
>>> def f (x):
... return x*2 ...
>>> F (3)
6
>>> g = Lambda x:x*2
>>> g (3)
6
>>> (Lambda x:x*2) (3)
61 This is a lambda function that completes the same thing as the normal function above. Note the short syntax here: there is no parentheses around the argument list, and the return keyword is ignored (implied because there is only one row for the entire function). Also, the function does not have a function name, but it can be assigned to a variable for invocation.
2 when using a lambda function, you do not even need to assign it to a variable. It's probably not the most useful thing in the world, it just shows that the lambda function is just an inline function
In general, a lambda function can receive any number of arguments, including optional arguments, and returns the value of a single expression. A lambda function cannot contain a command and cannot contain more than one expression. Don't try to cram too much into a lambda function; If you need something more complex, you should define a normal function and how long you want it to be.
2. How to use an LAMDA expression
Overall, the LAMDA expression is an anonymous function in Python, defines a function parameter, evaluates the result-but does not define a function name (which is why it is called an anonymous function). The LANMDA expression as a whole is equivalent to a function name, followed by parentheses to pass arguments to it.
But there are pros and cons. If you use a large number of lambda expressions in your program, the structure of your program is confusing, and if the lambda expression is too complex, it will cause the program to be very readable.
3. Why use Lamda Expressions
In many cases, we need to use function, but we are too lazy to define a function, at which point the LAMDA function will play.