Python从列表删除元素
时间:2020-02-23 14:43:44 来源:igfitidea点击:
在本教程中,我们将看到如何从Python列表中删除元素。
我们可以以3种方式从列表中删除元素。
使用列表对象的remove方法
其中我们需要指定要删除的元素。
如果有多个元素出现,则将删除第一次出现。
请注意,这非常慢,因为它在列表中搜索元素,然后按其值删除元素。
如果列表中不存在元素,则会引发valutierError。
list1=["Netherlands", 1, "Nepal", 2,5,1,2,3,4,3,2] list1.remove(2) print(list1) list1.remove(9) print(list1)
['Netherlands', 1, 'Nepal', 5, 1, 2, 3, 4, 3, 2] ————————————————————————— ValueError Traceback (most recent call last) in () 3 print(list1) 4 —-> 5 list1.remove(9) 6 print(list1) ValueError: list.remove(x): x not in list
使用列表对象的POP方法
此方法将元素索引作为输入并删除它。
如果索引超出范围,它会抛出IndexError。
list1=["Netherlands", 1, "Nepal", 2,5,1,2,3,4,3,2] list1.pop(2) print(list1) list1.pop(14) print(list1)
['Netherlands', 1, 2, 5, 1, 2, 3, 4, 3, 2] ————————————————————————— IndexError Traceback (most recent call last) in () 3 print(list1) 4 —-> 5 list1.pop(14) 6 print(list1)
IndexError:POP索引超出范围
使用运算符del.
此运算符将元素索引作为输入并删除元素。
Del运算符还支持从列表中删除元素范围。
这是清晰快捷的方式从列表中删除元素。
list1=["Netherlands", 1, "Nepal", 2,5,1,"France",2,3,4,3,2] del list1[2] print(list1) del list1[4:7] print(list1)
['Netherlands', 1, 2, 5, 1, 'France', 2, 3, 4, 3, 2] ['Netherlands', 1, 2, 5, 3, 4, 3, 2]