anonymous function-lambda in Python

Source: Internet
Author: User
Briefly

In addition to the DEF statement, Python provides a form of expression that generates a Function object. This expression creates a function that can then be called, but it returns a function instead of assigning the function to a variable name.

Lambda expression

The general form of a lambda is the keyword lambda, followed by one or more parameters, followed by a colon, followed by an expression: Lambda argument1 argument2 ...: expression using arguments

A lambda is an expression, not a statement.

As an expression, lambda returns a value that can optionally be assigned to a variable name. Instead, the DEF statement always assigns a new function to a variable name at the head, rather than returning the function as a result.

A lambda body is a single expression, not a block of code.

The default parameters can also be used in lambda parameters, just as they are used in def.

>>>x = (Lambda a = "www.", b = "Pythontab", c = ". com": A + b +c)

>>>x ("BBS")

' Bbs.pythontab.com '

Why use Lambda

1. When using Python to write some execution scripts, using lambda eliminates the process of defining a function and makes the code more streamlined.

2. For some abstract functions that are not reused elsewhere, sometimes it is difficult to name a function, and using lambda does not have to consider naming problems.

3. Using lambda makes the code easier to understand at some point.

  • 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.