On the 16th day of the November Gwen Challenge, check out the details: the last Gwen Challenge 2021

Boy, I used to be the front end, and WHEN I saw an anonymous function or an inline function, I felt DNA move.

In Python, I just familiarized myself with the basic syntax and started looking at deep learning, so I didn’t look at any inline functions. I was a little confused when I saw the code today. Looking it up, Python also has anonymous inline functions.

So what is an anonymous function?

lambda

An anonymous inline function consisting of a single expression that is evaluated when called. Lambda functions are created using the syntax lambda [parameters]: expression

Lambda keyword declaration followed by the argument list, : after the function body.

Note that parameters and expression are written here, which means lambda stands for anonymous function. Multiple parameters can be passed, but only one expression can be passed. Lambda [arg1…argk] : expression

Such as:

function = lambda a,b,c:a+b+c

print(function(1.1.1))
print(function(3.2.1))
Copy the code

Output:

> > 3 to 6Copy the code

Anonymous functions are not requiredreturnGets the return value. The expression itself results in the return value.

function = lambda x:x+1

print(function(1))
Copy the code

Output:

> > 2Copy the code

Equivalent to:

def function(x) :
    return x+1

print(function(1))
Copy the code

Output:

> > 2Copy the code

Function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function = function

No!

Like normal functions, an anonymous function is a function object. You can also assign an anonymous function to a variable and use the variable to call the function.

Function = is just a way to call an anonymous function and assign it to a variable. Here’s an example of a normal function assigned to a variable:

def function(x) :
    return x+1

f = function

print(f(1))
Copy the code

Output:

> > 2Copy the code

Therefore, the advantage of anonymous functions is that there is no need to name functions, which can prevent function name conflicts.

Some functions are only used once in the code, and the body of the function is simple, so using anonymous functions can reduce the amount of code and make the code look more “elegant.”