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

 

posted @   放氮气的蜗牛  阅读(222)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示