How to remove multiple items from a Python list?

How can I remove multiple items from a list in Python in a single statement?

In Python, I know how to remove individual items from a list like this:

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 I need to remove many items, I have to write multiple lines like this:

item_list.remove("something_to_remove")

If I know the index of the item I want to remove, I can use:

del item_list[x]

Where x is the index of the item to be removed. If I know the indices of the items to remove, I can loop through and use del for each one.

However, 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 accepts one argument.

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

Also, I’d appreciate an explanation of the difference between del and remove()—are they the same or do they serve different purposes?

I’ve been working with Python for years, and one of the cleanest ways to remove multiple items from a list is by using list comprehension. It’s straightforward and works like a charm when you know which items need to be excluded. Here’s an example:

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

This approach is fast and keeps your code concise. Perfect for filtering out unwanted elements in one go!

Building on Rashmi’s method, if you prefer using a function rather than a comprehension, Python’s filter() function is a great alternative. It works well with a lambda function to achieve the same result. Here’s how:

item_list = ['item', 5, 'foo', 3.14, True]
items_to_remove = ['item', 'foo']
item_list = list(filter(lambda x: x not in items_to_remove, item_list))
print(item_list)

This approach is just as effective but can feel more intuitive if you’re comfortable with functional programming. Plus, filter() can make your intent clearer in certain contexts.

Let’s take it a step further. If you’re dealing with situations where you can’t use comprehensions or filter(), a more manual approach using a loop and remove() can come in handy. It’s a bit verbose but gives you precise control. For example:

item_list = ['item', 5, 'foo', 3.14, True]
items_to_remove = ['item', 'foo']
for item in items_to_remove:
    while item in item_list:
        item_list.remove(item)
print(item_list)

While this method works, remember that remove() only deletes the first occurrence, so using a while loop ensures all instances are removed. It’s not the most efficient for large lists, but it gets the job done when you need full control.