How to Use lambda expressions in basic python tutorials

Source: Internet
Author: User
Lambda expressions are equivalent to an anonymous function of a common function whose function body is a single return statement. This article describes how to use lambda expressions in Python. if the function body is a separate return expression statement, developers can replace the function with a special lambda expression:

The code is as follows:


Lambda parameters: expression

A lambda expression is equivalent to an anonymous function of a common function whose function body is a single return statement. Note that the return keyword is not used in lambda syntax. Developers can use lambda expressions wherever function references are available. Lambda expressions are convenient when developers want to use a simple function as a parameter or return value. The following is an example of using a lambda expression as a parameter of the built-in filter function:

The code is 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 another option, developers can also use a local def statement that can name function variables. Then, developers can use this name as a parameter or return value. The following is an example of the same filter using the local def statement:

The code is 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]

Lambda expressions are only useful occasionally. many Python users prefer def and def to be more generic. if a developer selects a 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.