Python basic Tutorial: anonymous functions lambda and pythonlambda
Python lambda
When using a function, sometimes you do not need to define a function that is displayed. You can use an anonymous function to make it more convenient and support anonymous functions in Python.
For example, if we want to calculate two numbers a and B, that is, f (a, B) = a + B. We can do this in two ways. The first one is to define a function f (x, y), and then pass the parameter to get the result. The second method is to use an anonymous function.
f = lambda x,y:x+y >>>f(1,2) 3
The anonymous function lambda x, y: x + y is actually:
def f(x, y): return x + y
In python, the keyword lambda indicates an anonymous function, and x and y in front of the colon indicates the function parameters. The syntax of an anonymous function is:
lambda [arg1[,arg2,arg3....argN]]:expression
In a lambda statement, there are multiple parameters before the colon, which are separated by commas. The result of the expression on the right of the colon is used as the return value of the anonymous function.
An anonymous function has a limit that only one expression is allowed. return is not required. The return value of an anonymous function is the result of this expression. There is a benefit to using an anonymous function because the function has no name and you don't have to worry about function name conflicts. In addition, an anonymous function is also a function object. You can assign an anonymous function to a variable and use the variable to call the function:
>>> f = lambda x: x * x >>> f <function <lambda> at 0x101c6ef28> >>> f(5) 25
You can also use an anonymous function as the return value of the function, for example:
def build(x, y): return lambda: x + y
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!