python列表删除元素之del,pop()和remove()

del函数

如果知道要删除元素在列表中的位置,可以使用del语句:

list_1 = ['one', 'two', 'three']
print(list_1)

del list_1[0]
print(list_1)

根据索引,del语句删除了list_1列表中的第一个元素——'one'

['one', 'two', 'three']
['two', 'three']

要想使用del删除列表中的任意元素,前提是知道其索引(位置)

 

pop()

pop()顾名思义——弹出,弹出列表末尾的元素,并且使用这个弹出的元素:

list_1 = ['one', 'two', 'three']
print(list_1)

pop_list_1 = list_1.pop()
print(pop_list_1)
print(list_1)

这里使用pop()弹出了list_1列表的最后一个元素'three',并且把'three'赋值给了pop_list_1

['one', 'two', 'three']
three
['one', 'two']

当然,pop(索引)也可以弹出列表中的任意元素,前提是知道该元素的索引:

list_1 = ['one', 'two', 'three']
print(list_1)

pop_list_1 = list_1.pop(1)
print(pop_list_1)
print(list_1)

如del一般,这里弹出了列表的第二个元素(索引为1)

['one', 'two', 'three']
two
['one', 'three']

 

remove()

有时候我们不知道元素的索引的时候,但是知道要删除的这个元素是什么,那我们就可以用remove()这个方法

list_1 = ['one', 'two', 'three']
print(list_1)

list_1.remove('two')
print(list_1)

此时我们知道了要删除的元素是'two',那么我们用remove()得:

['one', 'two', 'three']
['one', 'three']

当然,和pop一样,被删除的元素我们依然可以使用:

list_1 = ['one', 'two', 'three']
print(list_1)

remove_1 = 'two'
list_1.remove(remove_1)
print(list_1)

print(remove_1.title())

我们先把要删除的元素'two'存储在remove_1中,然后再用remove()方法把remove_1中存储的值删除,但是元素'two'依然存储在变量remove_1中

['one', 'two', 'three']
['one', 'three']
Two

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放氮气的蜗牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值