



















If we pass list as parameter to a function and change the parameter, the original list is also changed. This is because list is a mutable type, when we pass list to a function, we are passing the same list.
def my_fun(my_list):
my_list.append(1)
return my_list
x = [1, 2, 3]
y = my_fun(x)
print(f"x: {x}, y: {y}")
# x, y are both [1, 2, 3, 1]How can we pass the “value” of this list instead of its “reference”? We can use several ways:
my_fun(x[:])my_fun(list(x))list.copy(): my_fun(x.copy())copy.copy(): my_fun(copy.copy(x))copy.deepcopy(): my_fun(copy.deepcopy(x))The first four ways only create a shallow copy of the original list. They only work for simple list consisting of immutable types, for example, a list of int. If the list element is a mutable type themselves, they will not work.
Only the copy.deepcopy() method can truly create a new list.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。