Python anonymous function--lambda expression

Source: Internet
Author: User

If the function to be defined is simple, a return statement can be done and can be defined using a lambda expression,

The syntax for a lambda expression is as follows:

Lambda parameters:expression

Lambda expressions do not contain return statements, and you can use lambda expressions wherever functions are used as parameters or return values, and the benefits of lambda functions are:

  • Easy and Handy
  • You can not name the function, some places do not need to reuse the function, essentially do not need to give the function to think of a name

The following example 1 takes the function defined by the lambda expression as a parameter to the built-in function filter.

Example 1. To use a lambda function as a parameter

>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> low = 3>>> High = 7>>> Filter (lambda x, L=low, H=HIGH:H>X>L), L) [4, 5, 6]

Example 1 directly to the defined lambda function as a parameter to the built-in function filter, you can also assign a lambda function to an identifier, convenient for future calls:

Example 2. Invoking a lambda function

>>> f = lambda x, y, z:x + y-z>>> f (1, 2, 3) 0

  

Python anonymous function--lambda expression

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.