python basic tutorial on the anonymous function lambda

  • 2020-05-19 05:11:29
  • OfStack

python lambda

When we use functions, sometimes, we don't need to show the definition of a function, we can use anonymous functions more conveniently, there is also support for anonymous functions in Python.

For example, when we want to calculate the sum of two Numbers a and b, f(a,b) = a + b. There are two ways to do this, the first is to show the definition of a function f(x,y), and then pass in the parameters to get the result. The second way is to use anonymous functions.


f = lambda x,y:x+y 
>>>f(1,2) 
3 

The anonymous functions lambda x,y:x+y are actually:


def f(x, y): 
  return x + y 

In python, the keyword lambda means the anonymous function. x before the colon and y mean the parameter of the function. The syntax of the anonymous function is:


lambda [arg1[,arg2,arg3....argN]]:expression

In lambda statements, the colon is preceded by a parameter, which can be multiple, separated by commas, and the result of the expression to the right of the colon is the return value of the anonymous function.

One of the limitations of an anonymous function is that it can have only one expression. Instead of writing return, the return value of the anonymous function is the result of the expression. The advantage of using anonymous functions is that they don't have a name and you don't have to worry about name collisions. In addition, an anonymous function is also a function object. You can also assign an anonymous function to a variable and call the function with the variable:


>>> f = lambda x: x * x 
>>> f 
<function <lambda> at 0x101c6ef28> 
>>> f(5) 
25 

At the same time, anonymous functions can also be returned as the return value of functions, such as:


def build(x, y): 
  return lambda: x + y  

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: