我见过很多人使用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
[]
>>>
答案 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'])
答案 1 :(得分:2)
我认为正在执行list=[]
会创建一个新的空列表,list[:]=[]
仍在同一列表中工作。
>>> array=[] >>> id(array) 32758680 >>> array[:]=[] >>> id(array) 32758680 >>> array=[] >>> id(array) 32758360 >>>