Original article: http://www.cnpythoner.com/post/140.html
Python defAndPython lambdaThere are also differences between these two similarities. 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 and supply programs to call them, for example, we need to define a method for adding a variable to 2.
First, look at python def.
Def info (x ):
Return x + 2
A = info (1)
Print
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
If a> 1:
Def info ():
Print 'hahaha'
Else:
Def test ():
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