clear list 和 list = [] 的区别

difference between clear list and list = []

我目前正在研究一位同事以前写的一些脚本,我的学士论文需要它们。

当我编写另一个脚本时遇到以下问题:

  listA = [......] #list is filled
  listB = listA
  listB.clear()

在这个 listA 也被清除后,我使用了它:

  listB = listA.copy()

我的同事在她的代码中这样做了

 listA = [.......] #list is filled
 listB = listA
     functoin(listB)
 listB = []

之后她仍然以一种从未被清空的方式使用listA。但是由于 python 通过引用复制并不意味着命令:

 listB = []

现在 listA 也是空的?

提前致谢

明确地说,当您 运行 您同事的代码时,会发生以下情况:

listA = [.......] # listA points to a list

listB = listA     # listB and listA are now 2 variables pointing to the SAME OBJECT

function(listB)   # this does the same as function(listA) would do
                  # only the object matters here, the function does not know the variable name

listB = []        # now listB points to a new object, an empty list.
                  # listA and the object to which it points remain the same