Fix Python – How to remove multiple items from a list in just one statement?

Question

Asked By – RandomCoder

In python, I know how to remove items from a list:

item_list = ['item', 5, 'foo', 3.14, True]
item_list.remove('item')
item_list.remove(5)

The above code removes the values 5 and ‘item’ from item_list.
But when there is a lot of stuff to remove, I have to write many lines of:

item_list.remove("something_to_remove")

If I know the index of what I am removing, I use:

del item_list[x]

where x is the index of the item I want to remove.

If I know the index of all of the numbers that I want to remove, I’ll use some sort of loop to del the items at the indices.

But what if I don’t know the indices of the items I want to remove?

I tried item_list.remove('item', 'foo'), but I got an error saying that remove only takes one argument.

Is there a way to remove multiple items from a list in a single statement?

P.S. I’ve used del and remove. Can someone explain the difference between these two, or are they the same?

Now we will see solution for issue: How to remove multiple items from a list in just one statement?


Answer

In Python, creating a new object e.g. with a list comprehension is often better than modifying an existing one:

item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]

… which is equivalent to:

item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
    if e not in ('item', 5):
        new_list.append(e)
item_list = new_list

In case of a big list of filtered out values (here, ('item', 5) is a small set of elements), using a set is faster as the in operation is O(1) time complexity on average. It’s also a good idea to build the iterable you’re removing first, so that you’re not creating it on every iteration of the list comprehension:

unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]

A bloom filter is also a good solution if memory is not cheap.

This question is answered By – aluriak

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0