Sobes.tech
Junior

What is the difference between the remove, del, and pop methods in Python?

sobes.tech AI

Answer from AI

  • remove(value): Removes the first occurrence of the specified value from the list. Raises ValueError if the value is not found.
  • del list[index] or del list[slice]: Removes an element or a slice at the specified index (or slice).
  • pop(index): Removes the element at the specified index from the list and returns it. If no index is specified, it removes and returns the last element. Raises IndexError if the index is out of range.
Method Effect Return Value By Value By Index
remove() Modifies the list in place None Yes No
del Modifies the list in place No No Yes (or slice)
pop() Modifies the list in place Removed element No Yes

Examples:

# remove()
my_list = [1, 2, 3, 2, 4]
my_list.remove(2) # Removes the first occurrence of 2
# my_list = [1, 3, 2, 4]
# del
my_list = [10, 20, 30, 40, 50]
del my_list[2] # Removes element at index 2 (value 30)
# my_list = [10, 20, 40, 50]
del my_list[1:3] # Removes slice from index 1 to 2 (values 20, 40)
# my_list = [10, 50]
# pop()
my_list = [100, 200, 300]
popped_item = my_list.pop(1) # Removes element at index 1 and returns it (value 200)
# my_list = [100, 300]
# popped_item = 200
last_item = my_list.pop() # Removes the last element and returns it (value 300)
# my_list = [100]
# last_item = 300