ZetCode

Python 列表 remove

最后修改于 2024 年 1 月 29 日

在本文中,我们将展示如何在 Python 中删除列表元素。

列表 是值的有序集合。它是一个可变集合。列表元素可以通过零基索引访问。

可以使用 removepopclear 函数以及 del 关键字删除列表元素。

Python 列表 remove

remove 函数删除给定值的第一个匹配项。如果值不存在,它会引发 ValueError

main.py
#!/usr/bin/python

words = ["sky", "cup", "new", "war", "wrong", "crypto", "forest",
         "water", "cup"]

print(words)

words.remove("cup")
print(words)

words.remove("cup")
print(words)

程序定义了一个单词列表。我们从列表中删除了两个单词。

$ ./main.py 
['sky', 'cup', 'new', 'war', 'wrong', 'crypto', 'forest', 'water', 'cup']
['sky', 'new', 'war', 'wrong', 'crypto', 'forest', 'water', 'cup']
['sky', 'new', 'war', 'wrong', 'crypto', 'forest', 'water']

Python 列表 pop

pop 函数删除并返回给定索引处的元素。如果未显式定义索引,则默认为最后一个。如果列表为空或索引超出范围,该函数会引发 IndexError

main.py
#!/usr/bin/python

words = ["sky", "cup", "new", "war", "wrong", "crypto", "forest",
         "water", "cup"]

w = words.pop(0)
print(f'{w} has been deleted')

w = words.pop()
print(f'{w} has been deleted')

print(words)

在程序中,我们使用 pop 删除两个单词。我们将删除的单词打印到控制台。

$ ./main.py 
sky has been deleted
cup has been deleted
['cup', 'new', 'war', 'wrong', 'crypto', 'forest', 'water']

Python 列表 clear

clear 方法删除列表中的所有项。

main.py
#!/usr/bin/python

words = ["sky", "cup", "new", "war", "wrong", "crypto", "forest",
         "water", "cup"]

print(f'there are {len(words)} words in the list')

words.clear()

print(f'there are {len(words)} words in the list')

程序使用 clear 函数。它还使用 len 计算列表元素的数量。

$ ./main.py 
there are 9 words in the list
there are 0 words in the list

Python 列表 del

另外,我们也可以使用 del 关键字删除给定索引处的元素。

main.py
#!/usr/bin/python

words = ["sky", "cup", "new", "war", "wrong", "crypto", "forest",
         "water", "cup"]

del words[0]
del words[-1]

print(words)

vals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del vals[0:4]

print(vals)

在程序中,我们使用 del 删除元素。

del words[0]
del words[-1]

我们删除了列表的第一个和最后一个元素。

vals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del vals[0:4]

在这里,我们删除了一系列整数。

$ ./main.py 
['cup', 'new', 'war', 'wrong', 'crypto', 'forest', 'water']
[4, 5, 6, 7, 8, 9, 10]

来源

Python 数据结构 - 语言参考

在本文中,我们展示了如何在 Python 中删除列表元素。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。到目前为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程