如何清空列表? [英] How to empty a list?

查看:86
本文介绍了如何清空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这种方式清空列表似乎很肮脏":

It seems so "dirty" emptying a list in this way:

while len(alist) > 0 : alist.pop()

是否存在明确的方法?

推荐答案

这实际上是从列表中删除内容,但不会用新的空列表替换旧标签:

This actually removes the contents from the list, but doesn't replace the old label with a new empty list:

del lst[:]

这是一个例子:

lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

出于完整性考虑,切片分配具有相同的效果:

For the sake of completeness, the slice assignment has the same effect:

lst[:] = []

它也可以用于缩小列表的一部分,同时替换一部分(但这超出了问题的范围).

It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).

请注意,执行lst = []不会清空列表,只是创建一个新对象并将其绑定到变量lst,但是旧列表仍将具有相同的元素,并且如果具有其他元素,效果将显而易见.变量绑定.

Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.

这篇关于如何清空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆