The usage of lambda in Python and the difference between it and Def _python

Source: Internet
Author: User
Tags python list in python

The lambda in Python is usually used to create anonymous functions in Python, and the method created with Def has a name, and in addition to the superficial method name, the lambda in Python has the following points and 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 the format of the Python lambda, which looks very streamlined.

Lambda X:print x

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

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

In this place there is no way to use the DEF statement directly instead. 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, which cannot be returned with return or defined behind a Python lambda. Therefore, statements such as if or for or print cannot be used in a lambda, and a lambda is generally used to define simple functions.

Here are a few examples of Python lambda:

1. The case of a single parameter:

g = lambda x*2
print g (3)

Run result is 6

2. The situation of multiple parameters:

m = Lambda x,y,z: (x-y) *z
print m (3,1,2)

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