是否有删除列表中所有元素的特定命令?

时间:2014-04-30 03:24:26

标签: python list

我知道你可以简单地说:

list = [a, b, c, d, e]

for index in list:
    list.remove(index)

但使用单个命令可以更快地实现:

list.remove(all)

或者其他什么东西?

3 个答案:

答案 0 :(得分:5)

您可以使用delExplain Python's slice notation

>>> lst = [1, 2, 3, 4]
>>> del lst[:]
>>> lst
[]
>>>
>>> lst = [1, 2, 3, 4]
>>> id(lst)
34212720
>>> del lst[:]
>>> id(lst)  # Note that the list object remains the same
34212720
>>>

答案 1 :(得分:1)

是的,你可以del myList[:]。 (不要使用list作为变量名,它会阻止对名为list的内置类型的访问。)

答案 2 :(得分:1)

我能想到的一种方式:

myList[:] = []

或者另一种方法是将None分配给列表,垃圾收集器最终会释放内存。

(“list”不是python中list的好名字,它已经是一个类型了)