Python列表中del,remove和pop有什么区别?
无论你在程序中写了多少行代码,当你想从Python列表中移除或删除任何元素时,你都需要考虑以下三个函数的区别: remove 、 del 和 pop ,并根据需要选择使用哪一个。
remove: remove()函数移除的是第一个匹配的值或对象,而不是一个特定的索引。例如,list.remove(value)
阅读更多:Python 教程
例子
list=[10,20,30,40]
list.remove(30)
print(list)
输出
[10, 20, 40]
del: del函数删除的是特定索引处的元素。例如,del list[index]
例子
list = [10,20,30,40,55]
del list[1]
print(list)
输出
[10, 30, 40, 55]
pop: pop函数删除的是特定索引处的元素,并返回该元素。例如,list.pop(index)
例子
list = [100, 300, 400,550]
list.pop(1)
print(list)
输出
[100, 400, 550]