Introduction to anonymous function usage in Python _python

Source: Internet
Author: User

When we pass in a function, there are times when we do not need to define the function explicitly, and it is more convenient to pass in the anonymous function directly.

In Python, you provide limited support for anonymous functions. Or take the map () function as an example, when you compute f (x) =x2, you can also pass in the anonymous function directly, in addition to the function that defines an F (x):

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

As you can see from the comparison, the anonymous function lambda x:x * x is actually:

def f (x): Return
  x * x

The keyword lambda represents an anonymous function, and the x in front of the colon represents the function argument.

There is a limit to the anonymous function, that is, there can be only one expression, and the return value is the result of the expression without a write-back.

There is a benefit to using an anonymous function because a function has no name and does not have to worry about a function name conflict. 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 call the function:

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

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

def build (x, y): Return
  lambda:x * x + y * y

Summary

Python has limited support for anonymous functions, and there are only a few simple cases where anonymous functions can be used.

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.