网站首页 > 技术文章 正文
列表基本上是 Python 中最常用的数据结构之一了,并且删除操作也是经常使用的。
那到底有哪些方法可以删除列表中的元素呢?这篇文章就来总结一下。
一共有三种方法,分别是 remove,pop 和 del,下面来详细说明。
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、数据结构、算法、编程、网络等各种常考题。
猜你喜欢
- 2025-01-05 Python教程:Python中列表的创建和删除详解
- 2025-01-05 Python轻松管理你的CSV文件:读取、写入、删除一步到位!
- 2025-01-05 Python——pandas删除指定行或列
- 2025-01-05 从 Python 列表中删除 NaN:完整指南
- 2025-01-05 Python文件、文件夹删除之os、shutil
- 2025-01-05 从 Python 字符串中删除特殊字符:完整指南
- 2025-01-05 YAML文件管理不再复杂:Python读取、修改、删除轻松搞定
- 2025-01-05 Python删除列表元素的3种方法,你都会吗?
- 2025-01-05 删除 Python 列表中的最后一个元素
- 2025-01-05 python目录、文件删除方法及详细示例
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)