list = []
和list.clear()
有什么区别?
根据我的代码的行为和我自己的观察,list.clear()
除去其条目以及用于附加其数据的条目。
示例:
container.append(list)
list.clear()
container
也将是[]
答案 0 :(得分:12)
调用clear
将从列表中删除所有元素。分配[]
只是将该变量替换为另一个空列表。当您有两个指向同一列表的变量时,这一点变得明显。
请考虑以下代码段:
>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]
与此相比:
>>> 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]
答案 1 :(得分:2)
如果您查看生成的字节码,也可以看到此信息。这里带有x = []
import dis
print("Exmaple with x = []")
s1 = """
x = [1,2,3]
x = []
"""
dis.dis(s1)
输出
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
由于我们有两个BUILD_LIST
,因此我们可以看到构建了两个列表。现在,我们来看看x.clear()
print("Exmaple with x.clear()")
s2 = """
x = [1,2,3]
x.clear()
"""
dis.dis(s2)
我们得到以下输出
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
此处仅构建了一个列表,并调用了clear,并且使用LOAD_CONST
将None
与初始值1,2,3
一样放置在堆栈上。