Anonymous functions in Python-lambda

Source: Internet
Author: User
In addition to the def statement, Python also provides an expression form for generating function objects. This expression creates a function that can be called later, but it returns a function without a brief description.

In addition to def statements, Python also provides an expression form for generating function objects. This expression creates a function that can be called later, but it returns a function instead of assigning this function to a variable name.

Lambda expressions

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

Lambda is an expression rather than a statement.

As an expression, lambda returns a value that can be selectively assigned to a variable name. On the contrary, the def statement always has to assign a new function to a variable name in the header, instead of returning the function as a result.

A lambda subject is a single expression rather than a code block.

Default parameters can also be used in lambda parameters, just as 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 can save the process of defining functions and simplify the code.

2. for some abstract functions that will not be reused elsewhere, it is also difficult to give them a name. you do not need to consider naming when using lambda.

3. use lambda to make the code easier to understand in some cases.

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.