Arc*_*nan 2 python list python-3.x
list = []和之间有什么区别list.clear()?
根据代码的行为和我自己的观察,list.clear()删除其条目以及用于添加其数据的条目。
例:
container.append(list)
list.clear()
Run Code Online (Sandbox Code Playgroud)
container 也将是 []
Mur*_*nik 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
[]
Run Code Online (Sandbox Code Playgroud)
与此相比:
>>> 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]
Run Code Online (Sandbox Code Playgroud)