python:remove,pop和del方法的區別
阿新 • • 發佈:2019-01-28
這三種方法都是list的刪除方法,其中remove是針對可變列表的元素進行搜尋刪除,而pop和del是針對可變列表的下標進行搜尋刪除。具體區別如下:
1. remove
remove(item)方法是直接對可變序中的元素進行檢索刪除,返回的是刪除後的列表,不返回刪除值(返回None)
>>>list1=[1,3,6,7,8]
>>>print list1.remove(3) #對列表元素進行搜尋刪除,而不是下表
>>>print list1
None
[1,6,7,8]
2. pop
pop(index)方法是對可變序列中元素下標進行檢索刪除,返回刪除值
>>>list1=[1,3,6,7,8]
>>>print list1.pop(3),#對列表下表進行檢索刪除
>>>print list1
7
[1,3,6,8]
>>>dict1={'Abby':21,'Bob':22,'cindy':21}
>>>print dict1.pop(1)
>>>print dict1
3. del
del(list[index])方法是對可變序列中元素下邊進行檢索刪除,不返回刪除值
>>>list1=[1,3 ,6,7,8]
>>>del list[3]
>>>print list1
[1.3,6,8]