Home  >  Article  >  Backend Development  >  What does lambda function mean in python?

What does lambda function mean in python?

藏色散人
藏色散人Original
2019-07-02 11:34:203601browse

What does lambda function mean in python?

There are two ways to define a function in Python. One is to define it in the conventional way, def, and the function must specify a name. The second method is to define it with lambda, which does not need to specify a name. It is called Lambda functions.

Lambda function is also called anonymous function. Anonymous function is a function without a name. Is it okay if the function does not have a name? Of course. If some functions are only used temporarily and their business logic is very simple, there is no need to give them a name.

Just like the extras in a movie, they often have very few roles. At most, they serve as foils for the leading actors and as minor actors. Do they need names? No, because they only appear temporarily and may not be needed next time, so there is no need to bother giving each of them a number and a name. After all, picking an elegant name is very laborious.

Let’s look at a simple lambda function first

>>> lambda x, y : x+y
 at 0x102bc1c80>

x and y are the two parameters of the function. The expression after the colon is the return value of the function. You can see at a glance that this function is I am trying to find the sum of two variables, but as a function, how can I use it without a name? Here we temporarily bind a name to this anonymous function, which makes it possible for us to call the anonymous function

>>> add = lambda x, y : x+y
>>> add
 at 0x102bc2140>
>>> add(1,2)
3

It is equivalent to a regular function

>>> def add2(x, y):
...     return x+y
...
>>> add2

>>> add2(1,2)
3

Related recommendations: "Python Tutorial

The above is the detailed content of What does lambda function mean in python?. 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