Remove Item from List in Python

Here are the 4 most common methods to remove an item from a list in Python:

(1) Using remove() method

The remove() method removes the first occurrence of a specified value from a list.

For example:

my_list = [10, 20, 30, 40]

# Remove the first occurrence of value 20
my_list.remove(20)
print(my_list) # Output: [10, 30, 40]

If the specified value appears multiples in a list, the remove() method only removes the first occurrence of the value.

For example:

my_list = [10, 20, 30, 10]

# Remove the first occurrence of value 10
my_list.remove(10)
print(my_list) # Output: [20, 30, 10]

If you try to delete an item that is not in the list, the remove() method raises ValueError. You can handle this error using the try and except block.

my_list = [10, 20, 30, 40]

try:
    # Trying to remove a value that doesn't exist in the list
    my_list.remove(50)
    print(my_list)
except ValueError:
    print("Error: Value doen't exist in the list.")

# Output: Error: Value doen't exist in the list.

(2) Using pop() method

The pop() method removes and returns the item at the specified index from a list.

For example:

my_list = [10, 20, 30, 40]

# Remove the first item from the list
my_list.pop(0)
print(my_list) # Output: [20, 30, 40]

Indices in Python start at the position 0.

If you do not pass index to the pop() method, it removes the last item of the list.

For example:

my_list = [10, 20, 30, 40]

# Remove the last item
my_list.pop()
print(my_list) # Output: [10, 20, 30]

(3) Using the del statement

The del statement in Python is used to delete objects. It can also remove elements from a list by index or slicing.

For example:

my_list = [10, 20, 30, 40]

# Remove the item at index 1
del my_list[1]
print(my_list) # Output: [10, 30, 40]

You can also use del to remove multiple elements from a list by specifying a slice.

my_list = [10, 20, 30, 40, 50]

# Remove list items from index 1 to 4
del my_list[1:4]
print(my_list) # Output: [10, 50]

When using slicing with del, the start index is inclusive (included in deletion), while the end index is exclusive (not removed).

The del statement can also delete the whole list.

my_list = [10, 20, 30, 40]

# Delete the whole list
del my_list
# print(my_list) # Raises NameError

If you try to access or print the list after deleting it, Python raises a NameError because the list no longer exists.

(4) Using clear() method

The clear() method removes all elements from the list, effectively making it empty.

For example:

my_list = [10, 20, 30, 40]

# Remove all the elements from the list
my_list.clear()
print(my_list) # Output: []

Choosing the right method

Use remove() when you know the value of the item you want to remove from the list.

Use pop() when you know the index of the item or need to retrieve the value of the removed item.

Use del() when you need to remove items by index or slice, or deleting the whole list.

Use clear() when you need to empty the list.