Lamda Expressions in Python

Source: Internet
Author: User

Python中的 lamda表达式 lambdastatements are used to create new function objects, and they are returned at run time.

python Lambda is the use of lambda in Python to create anonymous functions, and the method created with Def is named, except for the name of the method on the surface, Python lambda is not the same as the def?
1 python Lambda will
2 python Lambda It's just an expression, and DEF is a statement.

A lambda expression can have only one expression after ":". That is, in Def, return can also be placed behind a lambda, and cannot be returned with return can not be defined behind a Python lambda. Therefore, a statement such as if or for or print cannot be used in a lambda, and lambda is generally used only to define simple functions.

Use LAMDA form
<span style= "FONT-SIZE:18PX;" >def make_repeater (n):    return lambda s:s*ntwice = Make_repeater (2) print (twice (' word ')) print (twice (5)) </ Span>
How it works:

Here, we used the make_repeater function creates a new function object at run time and returns it. lambda statement is used to create a function object. Essentially, lambda requires a parameter (possibly multiple parameters), followed by only a single expression as the body of the function, and the value of the expression is returned by the new function. Note that even print Statement also cannot be used in lambda form, only expressions are used.


Let's look at more examples:

1 for single parameters:

g = Lambda x:x*2print (g (3))

The result is 6, the analysis (x is the formal parameter of the function, x*2 is the function body)

More than 2 parameters:

m = lambda x, y, Z: (x-y) *zprint (M (3,1,2)) (x, Y, Z is the function's formal parameter, (x-y) *z is the function body)

The result is 4 .


Lamda Expressions in Python

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.