Python Basic Tutorial anonymous function lambda

Source: Internet
Author: User
python Lambda

When we use functions, sometimes we do not need to show the definition of a function, we can use the anonymous function more convenient, in Python to the anonymous function also provides support.

For example, when we want to calculate the sum of two numbers, A and B, that is f (b) = a + We can do it in two ways, the first is to show the definition of 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 (3)

The 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, and the x, Y representation of the colon precedes the arguments of the function, and the syntax of the anonymous function is:

Lambda [arg1[,arg2,arg3....argn]]:expression

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

One limitation of an anonymous function is that there can be only one expression, and the return value of the anonymous function is the result of the expression without writing return. There is a benefit to using anonymous functions because the function does not have a name and does not have to worry about function name collisions. In addition, the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to invoke the function:

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

The anonymous function can also be returned as a function return value, such as:

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

Thank you for reading, hope to help everyone, thank you for the support of this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.