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

yizhihongxing

列表基本上是 Python 中最常用的数据结构之一了,并且删除操作也是经常使用的。

那到底有哪些方法可以删除列表中的元素呢?这篇文章就来总结一下。

一共有三种方法,分别是 removepopdel,下面来详细说明。

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

以上就是本文的全部内容,如果觉得还不错的话,欢迎点赞转发关注,感谢支持。


推荐阅读:

  • 计算机经典书籍
  • 技术博客 硬核后端开发技术干货,内容包括 Python、Django、Docker、Go、Redis、ElasticSearch、Kafka、Linux 等。
  • Go 程序员 Go 学习路线图,包括基础专栏,进阶专栏,源码阅读,实战开发,面试刷题,必读书单等一系列资源。
  • 面试题汇总 包括 Python、Go、Redis、MySQL、Kafka、数据结构、算法、编程、网络等各种常考题。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python 中删除列表元素的三种方法 - Python技术站

(0)
上一篇 2023年4月2日
下一篇 2023年4月2日

相关文章

  • Python 中的鸭子类型和猴子补丁

    原文链接: Python 中的鸭子类型和猴子补丁 大家好,我是老王。 Python 开发者可能都听说过鸭子类型和猴子补丁这两个词,即使没听过,也大概率写过相关的代码,只不过并不了解其背后的技术要点是这两个词而已。 我最近在面试候选人的时候,也会问这两个概念,很多人答的也并不是很好。但是当我向他们解释完之后,普遍都会恍然大悟:“哦,是这个啊,我用过”。 所以,…

    Python开发 2023年4月2日
    00
  • Python 报错 ValueError list.remove(x) x not in list 解决办法

    平时开发 Python 代码过程中,经常会遇到这个报错: ValueError: list.remove(x): x not in list 错误提示信息也很明确,就是移除的元素不在列表之中。 比如: >>> lst = [1, 2, 3] >>> lst.remove(4) Traceback (most recent …

    Python开发 2023年4月2日
    00
合作推广
合作推广
分享本页
返回顶部