Home > Backend Development > Python Tutorial > Example analysis of the difference between lambda and def usage in python

Example analysis of the difference between lambda and def usage in python

高洛峰
Release: 2017-03-11 10:07:47
Original
1497 people have browsed it

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
>>>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template