列表基本上是 Python 中最罕用的数据结构之一了,并且删除操作也是常常应用的。

那到底有哪些办法能够删除列表中的元素呢?这篇文章就来总结一下。

一共有三种办法,别离是 remove,pop 和 del,上面来具体阐明。

remove
L.remove(value) -> None – remove first occurrence of value. Raises ValueError if the value is not present.

remove 是从列表中删除指定的元素,参数是 value。

举个例子:

>>> lst = [1, 2, 3]>>> lst.remove(2)>>> lst[1, 3]

须要留神,remove 办法没有返回值,而且如果删除的元素不在列表中的话,会产生报错。

>>> lst = [1, 2, 3]>>> lst.remove(4)Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: list.remove(x): x not in list

pop

L.pop([index]) -> item – remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.

pop 是删除指定索引地位的元素,参数是 index。如果不指定索引,默认删除列表最初一个元素。

>>> lst = [1, 2, 3]>>> lst.pop(1)2>>> lst[1, 3]>>>>>>>>>>>> lst = [1, 2, 3]>>>>>> lst.pop()3

pop 办法是有返回值的,如果删除索引超出列表范畴也会报错。

>>> lst = [1, 2, 3]>>> lst.pop(5)Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: pop index out of range>>>

del
del 个别用在字典比拟多,不过也能够用在列表上。

>>> lst = [1, 2, 3]>>> del(lst[1])>>> lst[1, 3]

间接传元素值是不行的,会报错:

>>> lst = [1, 2, 3]>>> del(2)  File "<stdin>", line 1SyntaxError: cannot delete literal

del 还能够删除整个列表:

>>> lst = [1, 2, 3]>>> del(lst)>>>>>> lstTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'lst' is not defined

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注Python技术大本营,获取更多技能与教程。