目录
一、remove()
1.语法
list.remove(x) #删除指定元素x
2.示例代码
list = [1,2,3]
list.remove(2)
#list结果 [1, 3]
注意事项:remove删除列表中第一个匹配元素,若没有找到匹配元素会报错。
二、del
1.语法
del element
2.示例代码
list = [1,2,3]
del list[1]
#list结果 [1, 3]
注意事项:del 方法与remove函数相比更适合按照索引删除元素。
三、pop()
1.语法
list.pop([index])
删除索引指定的元素并将删除元素返回,若不指定索引位置则删除最后一个元素并返回该元素。
2.示例代码
list = [1,2,3]
x = list.pop(1)
print(x) # x = 2
print(list) # list结果 [1,3]
四、clear()
1.语法
list.clear()
清空列表,经常用于嵌套子列表的清空操作
2.示例代码
list = [[1,2,3],[4,5,6],[7,8,9]]
for sublist in list:
sublist.clear()
print('clear后的列表',list)
########
clear后的列表 [[], [4, 5, 6], [7, 8, 9]]
clear后的列表 [[], [], [7, 8, 9]]
clear后的列表 [[], [], []]
五、列表常用方法系列文章链接
关于列表的内置函数使用技巧相继推出了五篇文章,为方便大家知晓每篇文章的主讲内容。本部分列出主讲方法和相关链接。
主讲方法 | 文章链接 |
1.append()、extend()和insert()的详解 | Python列表常用方法一:append()、extend()和insert()的详解-优快云博客 |
2.remove()、del、pop()、clear()的详解 | Python列表常用方法二:remove()、del、pop()、clear()的详解_remove函数和pop函数和clear函数-优快云博客 |
3.sort()和sorted(),reverse()和reversed()的区别 | Python列表常用方法三:sort()和sorted(),reverse()和reversed()的区别-优快云博客 |
4.count()、index()函数 | Python列表常用方法四:count()、index()函数_count()index()-优快云博客 |
5.列表元素如何去掉重复项 | Python列表常用方法五:元素如何去掉重复项_将python 列表 去重-优快云博客 |