Python-anonymous function

Table of Contents

Preface

1. Definition of anonymous function

2. Syntax format of anonymous function

3. Implementation method

4. Application expansion of anonymous functions

5. Advantages of anonymous functions

6. The difference between named functions and anonymous functions


Foreword

What is an anonymous function? What are the application scenarios of anonymous functions? How to implement anonymous function?

1. Definition of anonymous function

An anonymous function is a function without a name. It is mainly used in situations where a function is needed but will not be needed later, let alone where you don’t want to bother naming the function. Normally, such a function is only used once.

2. Syntax format of anonymous function

name = lambda [arg1 [,arg2,...,argn]]:expression

The relevant parameters are as follows:

name: is used to call lambda expressions.

[arg1 [,arg2,…,argn]]: Optional parameter, used to specify the parameter list to be passed. Use commas “,” to separate multiple parameters.

expression: A required parameter, used to specify an expression that implements a specific function. If there are parameters, they will be applied in the expression.

3. Implementation method

Requirement: Change the following named functions to anonymous functions and call them

# Famous functions
def func(x, y):
    return x + y
  • To define an anonymous function, def cannot be used because def must be followed by a function name.
  • Defining anonymous functions requires the use of a new keyword – lambda.

Step 1: Define anonymous functions

# 1. The lambda keyword is directly followed by the parameters of the function.
# 2. It is also possible to directly assign values to parameters during the writing process. For example: y=1
# 3. After writing the parameters, we write a colon at the end
# 4. After writing, we can just write the subcode directly after the parameters.
# 5. The subcode of the function is a return value,
# 6. We can just remove the return and write the return value.
lambda x, y=1: x + y

Step 2: Call the anonymous function

  • The functions we defined earlier have a function name, which is equivalent to assigning the memory address of the defined function to the function name, so that we can access the function through the function name.
  • Anonymous functions have no names, but they also have memory addresses. Let’s try printing them to see.
print(lambda x, y=1: x + y)

>>>Output results:
<function <lambda> at 0x00000286F58FE438>
# You can see that this is a function address

Process finished with exit code 0
  • In this case, it is very simple if we want to call it, just add () directly at the end, and then when the parameters are added, we will pass them the parameters. For example 1,2.
  • But now there is a problem. If the parameter is passed directly after y, it will be recognized as: y(1, 2). So we first use parentheses to separate the entire previous function. Now run it and see what the result is.
(lambda x, y=1: x + y)(1, 2)

>>>Output results:

Process finished with exit code 0
  • The running result is nothing, because this function subcode only performs the operation of x + y, and there is no operation inside the function. Finally, it returns the operation result, which means that there is a return value after the function is called. So we can print it and try it.
print((lambda x, y=1: x + y)(1, 2))
# Because we gave a default value to y above, we can just pass one parameter to it and try it again.
print((lambda x, y=1: x + y)(1))

>>>Output results:
3
2

Process finished with exit code 0
  • Therefore, the call to the anonymous function is implemented.

4. Application expansion of anonymous functions

(1) Operational anonymous function

Quoting the above code, change the subcode to an operable anonymous function similar to print.

print((lambda x, y=1: print(x + y))(1))
# Because the function does not return a value, the result of the outermost print is None.

>>>Output results:
2
None

Process finished with exit code 0

(2) Single condition anonymous function

# If x>y output x, otherwise output y
print((lambda x, y=1: x if x > y else y)(3))
print((lambda x, y=1: x if x > y else y)(3, 6))

>>>Output results:
3
6

Process finished with exit code 0

(3) Multi-condition anonymous function

# If x>y output x, x<y output y, otherwise output both
print((lambda x, y=1: x if x > y else y if x < y else f'{x} {y}')(3))
print((lambda x, y=1: x if x > y else y if x < y else f'{x} {y}')(3, 6))
print((lambda x, y=1: x if x > y else y if x < y else f'x={x} y={y}')(1))

>>>Output results:
3
6
x=1 y=1

Process finished with exit code 0

(4) Multiple return value anonymous function

In (3), when we return two values, we directly use the f expression to integrate the two values into a whole string. Can we return the two values directly without modification?

# If x>y output x, x<y output y, otherwise output both
print((lambda x, y=1: x if x > y else y if x < y else x, y)(1))

>>>Output results:
Traceback (most recent call last):
  File "D:/1017-test.py", line 2, in <module>
    print((lambda x, y=1: x if x > y else y if x < y else x, y)(1))
NameError: name 'y' is not defined

Process finished with exit code 1
  • Obviously, an error was reported. The information given is “name ‘y’ is not defined”, which means that our y has not been defined yet. But when we wrote the parameters, we already gave y a default value. Why is it still said that we are undefined?
  • In fact, this is the difference between anonymous functions and named functions. The characteristic of anonymous functions is that when the first return value is obtained, the memory of the variable will be released, and the second return value cannot be obtained. Therefore, the conclusion drawn is that the return value of the anonymous function is not modified without modification. Two or more values cannot be returned directly.

5. Advantages of anonymous functions

  • When writing some scripts in Python, using lambda can save the process of defining functions and make the code more streamlined.
  • For some abstract functions that will not be reused elsewhere, sometimes it is difficult to name the function. There is no need to consider naming issues when using lambda.
  • Use lambda at some point then the code is easier to understand.

Example: Find a function that is the sum of two functions

Named function definition and call:

def add(x, y):
    return x + y


print(add(1, 2))

>>>Output results:
3

Process finished with exit code 0

Anonymous function definition and call:

print((lambda x, y: x + y)(1, 2))
# Or you can write like this
add = lambda x, y: x + y
print(add(1, 2))


>>>Output results:
3
3

Process finished with exit code 0

6. The difference between named functions and anonymous functions

  • Anonymous functions are not suitable for scenarios that require repeated calls, but require a function that only needs to be used temporarily.
  • Named function: needs to be called repeatedly.
  • Anonymous function: Called once temporarily, anonymous functions are generally used in conjunction with other functions and can only directly return a return value.

Statement: The above content is only for learning and communication. If there are any mistakes, please correct me! ! !

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeBasic grammarFunction 383,200 people are learning the system