Home > Article > Backend Development > python basic tutorial anonymous function lambda
python lambda
When we use functions, sometimes we don’t need to explicitly define a function. We can use anonymous functions for more convenience. In Python Support is also provided for anonymous functions.
For example, when we want to calculate the sum of two numbers a, b, that is, f(a,b) = a + b. We can do it in two ways. The first is to explicitly define 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(1,2) 3
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. The x and y before the colon represent the parameters of the function. The syntax of the anonymous function is:
lambda [arg1[,arg2,arg3....argN]]:expression
In the lambda statement, there are parameters before the colon. There can be multiple parameters, separated by commas. The result of the expression on the right side of the colon is used as the return value of the anonymous function.
One limitation of anonymous functions is that they can only have one expression. There is no need to write return. The return value of the anonymous function is the result of the expression. There is an advantage to using anonymous functions because the function has no name and you don't have to worry about function name conflicts. In addition, the anonymous function is also a function object. You can also assign the anonymous function to a variable and then use the variable to call the function:
>>> f = lambda x: x * x >>> f <function <lambda> at 0x101c6ef28> >>> f(5) 25
At the same time , you can also return anonymous functions as the return value of the function, for example:
def build(x, y): return lambda: x + y
Thank you for reading, I hope it can help everyone, thank you for your review of this article Site support!
For more articles related to python basic tutorial anonymous function lambda, please pay attention to the PHP Chinese website!