python basic tutorial anonymous function lambda

高洛峰
Release: 2017-02-21 10:37:51
Original
1914 people have browsed it

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
Copy after login

Anonymous function lambda x,y:x+y is actually:

def f(x, y): 
  return x + y
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template