In Python, del is a keyword while remove() and pop() are list methods. All these three are used for the same purpose but the way they operate differs. Let’s learn those differences now.
del:
It is used to remove an element from a list at a specified location i.e. index.
Example:
list= [1,3,5,7,9] del list[2] print(list)
Output:
We can delete the entire list using this del keyword and also use it to delete a specific range of elements i.e. using slicing.
Example:
list= [1,3,5,7,9] del list print(list) list= [1,3,5,7,9] del list[2:] print(list)
Output:
If we try to print any specific element which isn’t present in the list, then it throws an IndexError.
remove():
In this method, we directly pass the element we want to delete or remove, as an argument.
Example:
list= [1,3,5,7,9] list.remove(3) print(list)
Output:
If we try to print any specific element which isn’t present in the list, then it throws a ValueError.
pop():
The pop() method not only deletes the element at the specified position (index) but also returns it.
Example:
list= [1,3,5,7,9] print(list.pop(3)) print(list)
Output:
It also shows IndexError(pop index out of range) when the element we are trying to delete isn’t present in the list.
Note 1: The del keyword can delete one item as well as the entire list. Whereas, pop() and remove() can delete only one element at once.
Note 2: The pop() method returns us the deleted value, whereas, del and remove() doesn’t.