Python anonymous function (lambda)

Source: Internet
Author: User

In short, the lambda expression mentioned in programming is usually used in situations where a function is required but does not bother to name a function , that is, the anonymous function

When we pass in a function, there are times when we don't need to explicitly define a function, and it's easier to pass in an anonymous function directly.

In Python, there is a limited amount of support for anonymous functions. As an example of a map() function, when calculating f (x) =x2, in addition to defining a f(x) function, you can also pass in an anonymous function directly:

>>> list (map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) [1, 4, 9, 16, 25, 36, 49, 64, 81]

By contrast, the anonymous function lambda x: x * x is actually:

def f (x):     return x * x

The keyword lambda represents an anonymous function, preceded by a colon, that x represents a function parameter.

The anonymous function has a restriction that there can be only one expression, without writing return , and the return value is the result of that expression.

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:

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

Similarly, anonymous functions can be returned as return values, such as:

def build (x, y):     return Lambda: x * x + y * y
Python has more lambda limitations than many other languages, and the worst is that it can only consist of one expression. This limitation is mainly to prevent abuse, because when people find that lambda is very convenient, it is easier to abuse, but more can make the program look less clear, after all, everyone's understanding of the level of abstraction is different.

Python anonymous function (lambda)

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.