Python basics How to use lambda expressions _python

Source: Internet
Author: User
Tags in python

In Python, if the function body is a separate return expression statement, the developer can choose to replace the function with a special lambda expression form:

Copy Code code as follows:

Lambda parameters:expression

A lambda expression is an anonymous function that corresponds to the normal function of a function body as a single return statement. Note that the lambda syntax does not use the return keyword. The developer can use a lambda expression in any location where the function reference can be used. Lambda expressions are handy when developers want to use a simple function as a parameter or return a value. The following is an example of a parameter that uses a lambda expression as a built-in filter function:

Copy Code code as follows:

Alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Low = 3
High = 7
Filter (lambda x, L=low, H=high:h>x>l, alist) # returns: [4, 5, 6]

As an alternative, developers can also use a local DEF statement that can be named for a function variable. The developer can then use this name as a parameter or return value. The following is an example of the same filter using a local DEF statement:

Copy Code code as follows:

Alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Low = 3
High = 7
def within_bounds (value, L=low, H=high):
return h>value>l filter (Within_bounds, alist) #
Returns: [4, 5, 6]

Because lambda expressions are only occasionally useful, many Python users prefer to use Def, which is more general, and if the developer chooses a more reasonable name for the function, it makes the code more readable.

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.