Different Ways to remove an item from a Python List


Different Ways to remove an item from a Python List

Python has various methods to remove elements from the List. Python provides us various options to remove all items in one go, remove the items by index position, remove the items by its value, remove multiple items in one go, or remove/delete the variable itself. Let us try to understand all these ways:

Different Ways to remove an item from a Python List

The remove() method – remove a specific item

We use the remove method to remove the specific item from the list. It will remove item by its value. It will remove only the first occurrence of the item. In case you want to remove all occurrences of the items, you have to use list comprehensions. Remove items using list comprehensions is discussed in detail in this article below.

If the value in not available in the list, it will raise an error. To avoid this error, in operator to check the membership of the list can be used.

Removed the name Steve from the List.

In [1]:
namelist = ["Bill", "Steve", "Tim"]
namelist.remove("Steve")

print(namelist)
['Bill', 'Tim']

Removes only the first occurrence, if the item appears twice, then the second occurrence will not be removed.

In [2]:
namelist = ["Bill", "Steve", "Tim", "Steve"]
namelist.remove("Steve")

print(namelist)
['Bill', 'Tim', 'Steve']

Raises an error, if an item is not present in the list.

In [3]:
namelist = ["Bill", "Steve", "Tim"]
namelist.remove("Tom")

print(namelist)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-3fd841f2dc83> in <module>
      1 namelist = ["Bill", "Steve", "Tim"]
----> 2 namelist.remove("Tom")
      3 
      4 print(namelist)

ValueError: list.remove(x): x not in list

Using in operator to avoid error.

In [4]:
namelist = ["Bill", "Steve", "Tim"]
item_to_remove = "Tom"

if item_to_remove in namelist:
    namelist.remove("Tom")

print(namelist)
['Bill', 'Steve', 'Tim']

The pop() method – removes item using index position

The pop() method will remove the item by its index position. If no index position is provided, by default, the index position is -1, i.e. it will remove the last item from the list. Index position starts from 0 and negative index position can also be used.

If the provided index position does not exist, it will throw an error. It returns the item it removed.

Let us look at a few examples:

If no index position is provided, it removes the last item by default.

In [1]:
namelist = ["Bill", "Steve", "Tim"]
namelist.pop()
print(namelist)

It returns the item it removed in the “item_removed” variable.

In [2]:
namelist = ["Bill", "Steve", "Tim"]
item_removed = namelist.pop()

print(item_removed)
print(namelist)

Removes specific index position.

In [3]:
namelist = ["Bill", "Steve", "Tim"]
namelist.pop(1)
print(namelist)
['Bill', 'Tim']

Using negative index position.

In [4]:
namelist = ["Bill", "Steve", "Tim"]
namelist.pop(-3)
print(namelist)
['Steve', 'Tim']

Throws an error, if index position does not exist.

In [5]:
namelist = ["Bill", "Steve", "Tim"]
namelist.pop(3)
print(namelist)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-c532e2141c4a> in <module>
      1 namelist = ["Bill", "Steve", "Tim"]
----> 2 namelist.pop(3)
      3 print(namelist)

IndexError: pop index out of range

The del keyword

The del keyword can be used for two purposes

  1. To remove the specific index or slice:
    • With the del keyword, you have the option to specify the index position, it will remove the item from that index position. Index position can be positive starting from 0 or negative also, starting from -1 for the last item.
    • With the slice notation, we can delete multiple items in one go. Or, slice notation can also be used to clear the list, i.e. delete all items from the list.
  2. To delete the list completely: The list variable can also be deleted using the del keyword. For this, we do not specify any index position and use the square brackets. Just the variable name with del.

Removes the specified index.

In [1]:
namelist = ["Bill", "Steve", "Tim"]
del namelist[1]
print(namelist)

Negative index.

In [2]:
namelist = ["Bill", "Steve", "Tim"]
del namelist[-2]
print(namelist)

Remove multiple items using Slicing.

In [3]:
namelist = ["Bill", "Steve", "Tim", "Tom", "Elon"]
del namelist[1:3]
print(namelist)
['Bill', 'Tom', 'Elon']
In [4]:
namelist = ["Bill", "Steve", "Tim", "Tom", "Elon"]
del namelist[:3]
print(namelist)
['Tom', 'Elon']

Deletes the list completely.

In [5]:
namelist = ["Bill", "Steve", "Tim"]
del namelist
print(namelist)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-0b2d12c2c9b9> in <module>
      1 namelist = ["Bill", "Steve", "Tim"]
      2 del namelist
----> 3 print(namelist)

NameError: name 'namelist' is not defined

The clear() method – to empty the list

The clear() method removes all the items from the list. The list variable still exists with no data.

In [1]:
namelist = ["Bill", "Steve", "Tim"]
namelist.clear()
print(namelist)
[]

List Comprehension : Conditionally Remove Items

To remove the items that are specific to the condition, list comprehension can be used. For example, to remove the odd numbers, to remove the even numbers or to remove all the items with specific name from the list.

It will filter all the items that do not satisfy the condition and a new list will be created with the required data. The existing list will remain unchanged.

Let us understand with a few examples:

Filter odd numbers from List.

In [1]:
numbers = [1,2,3,4,5,6,7,8,9,10]
odd_numbers = [n for n in numbers if n % 2 == 1]

print(odd_numbers)
[1, 3, 5, 7, 9]

Filter even numbers from List.

In [2]:
numbers = [1,2,3,4,5,6,7,8,9,10]
even_numbers = [n for n in numbers if n % 2 == 0]

print(even_numbers)
[2, 4, 6, 8, 10]

Remove all occurrences of the name “Tom” from the list.

In [3]:
namelist = ["Bill", "Steve", "Tom", "Tom", "Elon"]
final_names = [name for name in namelist if name != "Tom"]

print(final_names)
['Bill', 'Steve', 'Elon']

References:

  1. Remove an item from a list in Python (clear, pop, remove, del)
  2. Python – Remove List Items