python列表clear()

时间:2020-02-23 14:42:53  来源:igfitidea点击:

在本教程中,我们将看到Python列表的clear方法。

Python列表clear方法用于从列表中删除所有项目。

Python列表clear()例子

我们只需使用Clear方法即可从列表中删除所有项目.Python Extend不会返回任何内容,但它实际上更新了原始列表。
让我们在简单的例子的帮助下了解这一点。

l=[1,2,3,4]
print("List before clear:",l)
l.clear()
print("List after clear:",l)

输出:

List before clear: [1, 2, 3, 4]
List after clear: []

如果我们使用的是Python 3.2或者更低,则在列表中找不到清晰的方法。
我们需要在这种情况下使用Del运算符。

l=[1,2,3,4,5]
print("List before clear:",l)
del l[:]
print("List after clear:",l)

输出:

List before clear: [1, 2, 3, 4, 5]
List after clear: []