Python列表中删除元素的三种方法
方法一:使用del语句删除元素(前提是知道要删除的元素的位置)
bicycles=['trek','cannondale','redline','specialized'] print('删除前') print(bicycles) print('删除后') delbicycles[1] print(bicycles)
输出
删除前 ['trek','cannondale','redline','specialized'] 删除后 ['trek','redline','specialized']
方法二:使用pop()删除列表末尾的元素
>>>listA=['a','b','c','a','b','c','a','b','c'] >>>w=listA.pop(3) >>>w 'a' >>>print(listA) ['a','b','c','b','c','a','b','c']
方法三:根据值使用remove()删除元素
bicycles=['trek','cannondale','redline','specialized'] print(bicycles) bicycles.remove('cannondale') print(bicycles)
输出
['trek','cannondale','redline','specialized'] ['trek','redline','specialized']