+ 1
What is the difference between del() and remove() methods of list?
del() and remove()
2 Answers
+ 12
remove() removes the first matching value or object. It does not do anything with the indexing. It just searches the object and deletes it. Example :
myList = [4, 2, 3, 2]
myList.remove(2)
print(myList)
This gives the output as [4, 3, 2]. It removed the 2 which occurred first. To remove all the 2's from the list you need to run a loop.
del() removes the item at a specific index. It is helpful for deleting all elements or a slice. Example :
myList = [4, 3, 3, 2]
del myList[1]
print(myList)
This gives the output as [4, 3, 2]. The 3 at index 1 is removed from the list.
Hope this clearly explains the difference !!
+ 2
There is also a pop() method, which removes items from a certain index.
myList.pop(3)
equals:
del myList[3]
But it is rather matter of taste which you prefer to use.
del myList[3] seemed to be slighty faster, operations are typically faster than methods.