Python列表删除元素del、pop()和remove()的区别小结

Scarlett ·
更新时间:2024-09-21
· 578 次阅读

前言

在python列表的元素删除操作中, del, pop(), remove()很容易混淆, 下面对三个语句/方法作出解释

del语句

del语句可以删除任何位置处的列表元素, 若知道某元素在列表中的位置则可使用del语句.

例:

>>> a = [3, 2, 2, 1] >>> del a[1] >>> a [3, 2, 1]

pop()方法

pop()可删除任意位置的元素并将其返回, 只需在括号内指定要删除元素的索引即可, 当括号内为空时则删除该列表最后一个元素并将其返回.

例1:

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

例2:

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

例3:

brand = ['nike', 'aj', 'adidas'] popped_brand = brand.pop() print("The brand I don't really wear is " + popped_brand. title() + "." )

执行结果:

The brand I don't really wear is Adidas.

可见: 如果希望从列表中删除元素后还能继续使用它,就用pop()方法

remove()方法

remove()方法可根据值删除元素, 若不知所要删除元素在列表中的位置时可用remove()删除, 需要注意的是remove()所删除的元素是列表中第一个配对的值

例:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对软件开发网的支持。

您可能感兴趣的文章:python dict remove数组删除(del,pop)对python中数组的del,remove,pop区别详解python删除列表元素的三种方法(remove,pop,del)



小结 del remove pop python列表 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号