December 11, 2017
Difference between del remove and pop in Python
Introduction
In today’s Python code snippet, we are going to talk about deleting, removing and popping list elements:
- remove method: takes a value as input, searches for it, removes the first match. If the item is not found it errors out
- del function: removes an item at a specific index, can delete all elements or a slice
- pop method: by default, it removes and returns the last element but you can pop any element by providing an index
1 |
ValueError: list.remove(x): x not in list |
Here are few examples to demonstrate that:
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# (1) Remove an item with index A = [1, 2, 4, 3, 4] A.remove(4) # This will print [1, 2, 3, 4] print("Example 1 : A = {}".format(A)) # (2) Delete an item with index A = [1, 2, 4, 3, 4] del A[2] # This will print [1, 2, 3, 4] print("Example 2 : A = {}".format(A)) # (3) Delete all items A = [1, 2, 4, 3, 4] del A[:] # This will print [] print("Example 3 : A = {}".format(A)) # (4) Delete a slice 2, 4 A = [1, 2, 4, 3, 4] del A[1:3] # This will print [1, 3, 4] print("Example 4 : A = {}".format(A)) # (5) pop: remove and get the last item A = [1, 2, 4, 3, 4] x = A.pop() # This will print [1, 2, 4, 3] print("Example 5 : A = {}".format(A)) # This will print 4 print("Example 5 : x = {}".format(x)) # (6) pop with index: remove and get the second item A = [1, 2, 4, 3, 4] x = A.pop(1) # This will print [1, 4, 3, 4] print("Example 6 : A = {}".format(A)) # This will print 2 print("Example 6 : x = {}".format(x)) |
Removing objects
The remove method searches the list for a value (ex. integer, character, string). If the item to be removed is an object then it has to implement the equality operator so that it can be searched for. You need to add the following method to your class definition:
1 2 |
def __eq__(self, other): return self.name == other.name |
Running Time
Computational complexity (i.e. running time or Big-O) is as follows:
- del O(n)
- pop O(1)
- remove O(n)
Note that these running times are the worst case scenarios. For example, deleting an element at the beginning of the list takes constant time.
Summary
Here is a quick summary:
Syntax |
---|
Remove item at index: mylist.remove(index) |
Delete item at index: del mylist[index] |
Remove and get last item: x = mylist.pop() |