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

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

列表基本上是 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
复制代码


以上就是本文的全部内容。


目录
相关文章
|
18小时前
|
BI Python
深入浅出:讲解Python中的列表推导式
深入浅出:讲解Python中的列表推导式
|
19小时前
|
监控 PHP Python
1688快速获取整店铺列表 采集接口php Python
在电子商务的浪潮中,1688平台作为中国领先的批发交易平台,为广大商家提供了一个展示和销售商品的广阔舞台;然而,要在众多店铺中脱颖而出,快速获取商品列表并进行有效营销是关键。
|
1天前
|
Python
【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
【5月更文挑战第6天】【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
|
1天前
|
算法 Python
Python中不使用sort对列表排序的技术
Python中不使用sort对列表排序的技术
10 1
|
1天前
|
Python
【Python 基础】列表(list)和元组(tuple)有什么区别?
【5月更文挑战第6天】【Python 基础】列表(list)和元组(tuple)有什么区别?
|
1天前
|
算法 Python
从原始边列表到邻接矩阵:使用Python构建图的表示
从原始边列表到邻接矩阵:使用Python构建图的表示
3 0
|
1天前
|
数据处理 Python
Python中每个字段增加多条数据的高效方法
Python中每个字段增加多条数据的高效方法
6 1
|
1天前
|
机器学习/深度学习 存储 数据挖掘
Python中遍历并修改列表的综合指南
Python中遍历并修改列表的综合指南
8 2
|
1天前
|
机器学习/深度学习 自然语言处理 Python
python分词列表转化成词向量
python分词列表转化成词向量
7 1
|
测试技术 Android开发 Python