The use of lambda in Python and its differences with DEF

Source: Internet
Author: User
Tags python list
Lambda in Python is typically used to create anonymous functions in Python, and the method created with Def is named, except for the names of the methods on the surface, where the lambda in Python is not the same as the def:

1. python lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable.

2. Python Lambda It's just an expression, and DEF is a statement.

The following is a Python lambda format that looks very streamlined.

Lambda X:print x

If you use Python lambda in the Python list parsing, it doesn't feel very significant, because Python lambda creates a function object, but discards it immediately, because you're not using its return value, which is the function object. It is also because Lambda is just an expression that can be directly a member of a Python list or a Python dictionary, such as:

info = [Lamba a:a**3, Lambda B:b**3]

There is no way to replace the DEF statement directly in this place. Because DEF is a statement, not an expression that cannot be nested inside, a lambda expression can have only one expression after ":". That is, in Def, return can also be placed behind a lambda, and cannot be returned with return can not be defined behind a Python lambda. Therefore, a statement such as if or for or print cannot be used in a lambda, and lambda is generally used only to define simple functions.

Here are some examples of Python lambda:

1. The case of a single parameter:

g = Lambda X*2print g (3)

Operation result is 6

2. Conditions for multiple parameters:

m = lambda x, y, Z: (x-y) *zprint m (3,1,2)

Operation result is 4

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