Home Remove every occurrence of an item from a list in Python
Post
Cancel

Remove every occurrence of an item from a list in Python

A problem that I come across quite often is having to remove every occurrence of a given item from a Python list. While built-in mutable types have a remove() method, my_list.remove(x) only removes the first occurrence of item x from my_list.

Here is the pattern I use for removing every occurrence of a given item from a list:

1
2
3
4
5
6
7
8
9
10
def remove_all(items, item_to_remove):
    if not isinstance(items, list):
        raise TypeError(f'invalid list type {type(items).__name__}')

    last_occurrence = False
    while not last_occurrence:
        try:
            items.remove(item_to_remove)
        except ValueError:
            last_occurrence = True

The documentation states that remove() raises a ValueError when the item to remove is not found in the list.

In remove_all(), we take advantage of this. When a ValueError is raised, it means the item is no longer in the list or, in other words, that we have managed to remove every occurrence of that item from the list.

Example:

1
2
3
4
5
6
In [217]: items = [1, 2, 3, 1, 4, 5, 1, 6, 1, 7]

In [218]: remove_all(items, 1)

In [219]: items
Out[219]: [2, 3, 4, 5, 6, 7]

As can be seen above, remove_all() changes the input list items.

This post is licensed under CC BY 4.0 by the author.

How to return a result from a Python thread

Const and pointers in C++

Comments powered by Disqus.