python list删除元素的几种方式

假设我们有一个列表 a=[1,2,3,4,1,2,4,5]

指定元素进行删除

remove(x)

remove() 函数用于移除列表中 某个值的第一个匹配项,如果有多个则删除第一个 ,
注意list中不存在x,执行会报错
无法指定位置进行删除

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


指定位置进行删除

pop(index)

删除index位置上的元素,并返回该位置上的元素值
如果index越界则会报错

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

del x[index]

和pop所实现的功能是一样的,但是这个没有返回的值

>>> a=[1,2,3,4,1,2,4,5]
>>> del a[-1]
>>> a
[1, 2, 3, 4, 1, 2, 4]
>>> del a[-10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值