Home  >  Article  >  Backend Development  >  How to use python lambda function

How to use python lambda function

silencement
silencementOriginal
2019-06-21 10:38:332609browse

How to use python lambda function

The examples in this article describe the basic usage of Python lambda function. Share it with everyone for your reference, the details are as follows:

Here we briefly learn the python lambda function.

First, take a look at the syntax of the python lambda function, as follows:

f=lambda [parameter1,parameter2,……]:expression

In the lambda statement, there are parameters before the colon. There can be 0 or more, separated by commas. The right side of the colon is return value. What the lambda statement constructs is actually a function object.

1.No parameters

f=lambda :'python lambda!'
>>> f
 at 0x06BBFF30>
>>> f()
'python lambda!'

2.With parameters, no default value

f=lambda x,y:x+y
>>> f(3,4)
7

3.With parameters, there is a default value

f=lambda x=2,y=8:x+y
>>> f
 at 0x06C51030>
>>> f()#x取默认值2,y取默认值8
10
>>> f(1)#x取1,y取默认值8
9
>>> f(3,3)#x,y均取值3
6

The function returned by lambda can also be used as a parameter of another function

sumxy=lambda x,y:x+y
def test(f,m,n):
  print f(m,n)
>>> sumxy(4,5)
9
>>> test(sumxy,4,5)
9

The above is the detailed content of How to use python lambda function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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