Home > Article > Backend Development > 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 <function <lambda> 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 <function <lambda> at 0x102bc2140> >>> add(1,2) 3
It is equivalent to a regular function
>>> def add2(x, y): ... return x+y ... >>> add2 <function add2 at 0x102bc1c80> >>> 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!