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