Difference between del, remove, and pop on lists

  1. del: The del keyword is used to remove an item from a list by its index. It can also be used to remove a slice of items from a list. Example:
# Removing the first item from a list
my_list = [1, 2, 3, 4, 5]
del my_list[0]
print(my_list) # [2, 3, 4, 5]

# Removing a slice of items from a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
del my_list[1:4]
print(my_list) # [1, 5, 6, 7, 8]

Watch a course Python - The Practical Guide

  1. remove: The remove() method is used to remove an item from a list by it's value. It only removes the first occurrence of the item in the list. Example:
# Removing a specific item from a list
my_list = [1, 2, 3, 4, 5, 2]
my_list.remove(2)
print(my_list) # [1, 3, 4, 5, 2]
  1. pop: The pop() method is used to remove an item from a list by its index and return the removed item. If no index is provided, it removes and returns the last item of the list. Example:
# Removing and returning the last item of a list
my_list = [1, 2, 3, 4, 5]
removed_item = my_list.pop()
print(my_list) # [1, 2, 3, 4]
print(removed_item) # 5

# Removing and returning a specific item from a list
my_list = [1, 2, 3, 4, 5]
removed_item = my_list.pop(1)
print(my_list) # [1, 3, 4, 5]
print(removed_item) # 2

Note: del, remove, and pop are all used for removing items from a list, but each of them works in a different way and has different use cases. del is used to remove items by their index or slice, remove is used to remove items by their value, and pop is used to remove items by their index and return the removed item.