Python def and Lambda applications

Source: Internet
Author: User

There are also differences between Python def and Python lambda. Let's share your experiences today.
Let's talk about two similarities: these two very important similarities are that they can both define some fixed methods or processes to provideProgramFor example, we want to define a variable plus 2.
First, look at Python def.

Def Info (x ):
Return X + 2

A = Info (1)
PrintA
 

 

Let's look at Python lambda.
F = Lambda X: x + 2
A = F (1)
Print

The output result of the above two methods is 3. If you want to complete some fixed processes, you can choose either of the above two methods.

The similarities are mentioned above. Let's talk about the differences.
The main difference between them is that python def is a statement and Python Lambda is an expression. Understanding this is very important for you to understand them. Let's take a look at their applications.
First, the statements in python can be nested. For example, if you need to define a method based on a certain condition, you can only use def.
If you use lambda, an error is reported.

A = 2

IfA>1:
DefInfo ():
Print 'Hahaha'
Else:
DefTest ():
Print 'Test'
 

Sometimes, when you need to operate in a python expression, you need to use expression nesting. In this case, Python def cannot get the desired result, so you can only use Python lambda.
The following is an example:
G = Lambda X: x + 2
Info = [g (x) for X in range (10)]
Print info

Through the above example, we hope you can understand the similarities and differences between Python def and lambda. If you are interested in Python functions, you can see: Python function return values, Python function parameters

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

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.