Python Learning note 010--anonymous function lambda

Source: Internet
Author: User

1 syntax
Lambda arg1, arg2:arg1 + arg2 + 1

Arg1, arg2: Parameters

Arg1 + arg2 + 1: expression

2 description

The anonymous function does not need a return value, and the expression itself results in a return value.

Lambda is simply code-less and does not improve program performance

If you can use for ... in ... if To complete, it is best not to use the anonymous function lambda

When using lambda, the function does not include loops, nesting, or, if it does exist, it is best to use the DEF function, which makes the code more readable and reusable

Lambda is used to write simple functions, and DEF is used to handle more powerful tasks.

3 Example 3.1 anonymous function with no parameters
Lambda:5>>> a<function <lambda> at 0x7f20f53be2f0>>>>  A ()
3.2 Anonymous functions for single parameters
Lambda x:x+1print(A (2))

Run: 3

3.3 Anonymous functions with multiple parameters
Lambda x, y:x + y + 1print(A ())print(A (y=3,x=2))

Run:

46
3.4 Other
1 Lambda x:x+1 (1)2 <function <lambda> at 0x7f20f4cfb9d8>

Some blogs say that the first line of input can directly get the result, in fact, only get the address of the anonymous function (hex)

Lambda x:x+1 (1)<function <lambda> at 0x7f20f4cfb9d8>>>> ID (  Lambda x:x+1 (1))139779554729768>>> hex (ID (lambda x:x+1 (1)))'  0x7f20f4cfb9d8'

If the function value needs to be obtained, the

>>> (Lambda x:x+1) (1)2

Same

Print (Lambda x:x+1 (1))    # <function <lambda> at 0x7fa097b54f28> Print (Lambda x:x+1) (1))   # 2

Calculation

( lambda x: ( Lambda y: (lambda z:x + y + z) (1)) (2)) (3)

equals how much? 6

Refer to Python's anonymous function lambda interpretation and usage, Python learning Note (12): lambda expression and functional programming, Python lambda introduction

Python Learning note 010--anonymous function lambda

Related Article

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.