The difference between passing by value and passing by reference in python

In Python, passing by value and passing by reference are two concepts about function parameter passing.
        Pass by Value refers to copying the value of the parameter and passing it inside the function when the function is called. This means that changes to parameter values ​​inside the function will not affect variables outside the function. For example:

def change_value(x):
    x = 10
 num = 5
change_value(num)
print(num)  # 输出: 5
# 在这个例子中, `num` 是一个整数变量。当调用 `change_value` 函数时,函数参数 `x` 接收到了 `num` 的值,但在函数内部对 `x` 的修改并不会影响到 `num` 的值。

        Pass by Reference refers to passing the reference (memory address) of the parameter to the inside of the function when the function is called. This means that changes to parameter values ​​inside the function will affect variables outside the function. For example:

def change_list(lst):
    lst.append(4)
 my_list = [1, 2, 3]
change_list(my_list)
print(my_list)  # 输出: [1, 2, 3, 4]
# 在这个例子中, `my_list` 是一个列表变量。当调用 `change_list` 函数时,函数参数 `lst` 接收到了 `my_list` 的引用,因此在函数内部对 `lst` 的修改也会影响到 `my_list` 。

        It should be noted that the passing method in Python is actually passing by value. For immutable types (such as integers, strings, tuples, etc.), a copy of the value is passed, so modifications to the parameters inside the function will not affect variables outside the function. For variable types (such as lists, dictionaries, etc.), a copy of the reference is passed, so modifications to the parameters inside the function will affect the variables outside the function.

        Hope the above explanation is helpful to you! If you have additional questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/weixin_49786960/article/details/131706157