清除列表的这两种方法有什么区别?

时间:2014-04-26 23:18:37

标签: python arrays list

我见过很多人使用list[:] = []list = []将列表设为空。但是,两者有什么区别?

list[:] = []

>>> array = []
>>> array.append(9)
>>> array.append(4)
>>> array
[9, 4]
>>> array[:] = []
>>> array
[]

list = []

>>> array = []
>>> array.append(9)
>>> array.append(4)
>>> array
[9, 4]
>>> array = []
>>> array
[]
>>> 

2 个答案:

答案 0 :(得分:4)

list[:] = []表示使用RHS上的iterable中的项替换list的所有值(在本例中为none),它会影响该列表对象的所有引用。另一方面,list = []只是一个新的任务。

In [114]: a = b = [1, 2, 3]

In [115]: c = d = ['a', 'b', 'c']

In [116]: a[:] = []  

In [117]: a, b         #affects all references
Out[117]: ([], [])

In [118]: c = ['foo'] #decrements one reference count from the list pointed by `d`  

In [119]: c, d        #d is unaffected
Out[119]: (['foo'], ['a', 'b', 'c'])

相关:What is the difference between a[:]=b and a=b[:]

答案 1 :(得分:2)

我认为正在执行list=[]会创建一个新的空列表,list[:]=[]仍在同一列表中工作。

>>> array=[]
>>> id(array)
32758680
>>> array[:]=[]
>>> id(array)
32758680
>>> array=[]
>>> id(array)
32758360
>>>