View Python Lambda

Source: Internet
Author: User
Tags python list

Python LambdaIn python, lambda is used to create anonymous functions. The method created with Def is named. Apart from the method names on the surface, what are the differences between Python Lambda and def?

1. Python Lambda creates a function object, but does not assign this function object to an identifier. Def assigns the function object to a variable.
2. Python Lambda is just an expression, while def is a statement.

The following is a simplified Python Lambda format.
Lambda X: Print x

If you use Python Lambda in Python list parsing, it doesn't make much sense, because Python Lambda creates a function object, but it is discarded immediately, because you didn't use its return value, that is, the function object. Lambda is just an expression that can be directly used as a member of the python list or Python dictionary, for example:

Info = [Lambda A: A ** 3, Lambda B: B ** 3]

There is no way to directly replace it with the def statement. Because def is a statement, not an expression that cannot be nested in it, lambda expressions can only have one expression after. That is to say, in def, return can be returned or placed behind lambda. return cannot be used or defined behind Python lambda. Therefore, statements such as if, for, or print cannot be used in Lambda. Lambda is generally only used to define simple functions.

Here are some examples of Python lambda.
1. For a single parameter:
G = Lambda X: x * 2
Print G (3)
The result is 6.

For more than 2 parameters:
M = Lambda X, Y, Z: (x-y) * z
Print M (3, 1, 2)
Result 4

Nothing to writeProgramWhen using Python lambda, you will be familiar with it ..

OriginalArticlePlease indicate Reprinted from Old Wang python, this article address: http://www.cnpythoner.com/post/97.html

Author: Lao Wang @ Python tutorial
Old Wang Python provides Python-related Django tutorials and Python downloads!

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.