Home > Article > Backend Development > Example analysis of the difference between lambda and def usage in python
This article mainly introduces the comparison of the usage of lambda and def in python. It analyzes the difference and usage skills between lambda and def with examples. It has certain reference value. Friends in need can refer to the following
Comparison of examples in this article Analyzed the usage of lambda and def in python. Share it with everyone for your reference. The specific analysis is as follows:
1. Lambda is used to create anonymous functions, which is different from def (functions created by def all have names).
2. Lambda will not assign the result to an identifier, but def will assign the function result to an identifier.
3. Lambda is an expression, and def is a statement
Sample program:
>>> f1 = lambda x,y,z: x*2+y+z # lambda带有多个参数 >>> print f1(3,2,1) 9 >>> f3 = lambda i:i*2 # lambda带有一个参数 >>> print f3(7) 14 >>> def fun1(n): ... return lambda m:m**n # m的n次方 ... >>> def fun2(m, n): ... return m+n ... >>> f2 = fun1(2) # 动态生成一个函数 >>> print f2(4) 16 >>> print fun2(3, (lambda x:x+1)(2)) # lambda用作函数参数 6 >>>
The above is the detailed content of Example analysis of the difference between lambda and def usage in python. For more information, please follow other related articles on the PHP Chinese website!