W3docs

Difference between del, remove, and pop on lists

del: The del keyword is used to remove an item from a list by its index.

  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:

Using the del keyword in Python to remove an item or a slice of items from a list

# 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]

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

  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:

Using the remove function in Python to remove an item from a list by it's value

# 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:

Using the pop method to remove an item from a list by its index or removing the last item of a list in Python

# 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.