Python 中删除列表元素的三种方法

本文介绍了Python中删除列表元素的三种方法:remove、pop和del。remove方法根据值删除元素,若元素不存在则抛出ValueError;pop方法通过索引删除元素,可选参数指定索引,无参数时默认删除最后一个元素;del关键字可直接按索引或整个列表删除元素,误删会导致错误。详细示例展示了各种用法和注意事项。
摘要由CSDN通过智能技术生成

列表基本上是 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 1
SyntaxError: cannot delete literal

del 还可以删除整个列表:

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

以上就是本文的全部内容,如果觉得还不错的话,感谢支持。

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值