简体   繁体   English

list = [] 与 list.clear() 之间的区别

[英]Difference between list = [] vs. list.clear()

What is the difference between list = [] and list.clear() ? list = []list.clear()有什么区别?

Base on the behavior of my code and my own observation, list.clear() removes its entries and also the entries I used to append its data.根据我的代码行为和我自己的观察, list.clear()删除了它的条目以及我用来附加其数据的条目。

Example:例子:

container.append(list)
list.clear()

container will also be [] container也将是[]

Calling clear removes all the element from the list.调用clear从列表中删除所有元素。 Assigning [] just replaces that variable with another empty list.分配[]只是用另一个空列表替换该变量。 This becomes evident when you have two variables pointing to the same list.当您有两个变量指向同一个列表时,这一点就很明显了。

Consider the following snippet:考虑以下片段:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]

As compared to this one:与这个相比:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1 = []
>>> l1 # l1 is obviously empty
[]
>>> l2 # But l2 still points to the previous value, and is not affected
[1, 2, 3]

You can also see this if you take a look at the bytecode that is generated.如果查看生成的字节码,您也可以看到这一点。 Here the part with x = []这里x = []的部分

import dis

print("Example with x = []")

s1 = """
x = [1,2,3]
x = []
"""

dis.dis(s1)

which outputs哪个输出

Exmaple with x = []
  2           0 LOAD_CONST               0 (1)
              2 LOAD_CONST               1 (2)
              4 LOAD_CONST               2 (3)
              6 BUILD_LIST               3
              8 STORE_NAME               0 (x)

  3          10 BUILD_LIST               0
             12 STORE_NAME               0 (x)
             14 LOAD_CONST               3 (None)
             16 RETURN_VALUE

we can see that two lists are build since we have two BUILD_LIST .我们可以看到构建了两个列表,因为我们有两个BUILD_LIST Now if we take a look at x.clear()现在,如果我们看一下x.clear()

print("Exmaple with x.clear()")

s2 = """
x = [1,2,3]
x.clear()
"""

dis.dis(s2)

we get the following output我们得到以下输出

Exmaple with x.clear()
  2           0 LOAD_CONST               0 (1)
              2 LOAD_CONST               1 (2)
              4 LOAD_CONST               2 (3)
              6 BUILD_LIST               3
              8 STORE_NAME               0 (x)

  3          10 LOAD_NAME                0 (x)
             12 LOAD_ATTR                1 (clear)
             14 CALL_FUNCTION            0
             16 POP_TOP
             18 LOAD_CONST               3 (None)
             20 RETURN_VALUE

and here only one list is build and clear is called and LOAD_CONST is used to place None onto the stack as with the initial values 1,2,3 .这里只有一个列表被构建并被调用,并且LOAD_CONST用于将None放入堆栈,就像初始值1,2,3一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM