Remove multiple items from a Python list in just one statement
In Python, creating a new object 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.
You can do it in one line by converting your lists to set
s and using set.difference
:
item_list = ['item', 5, 'foo', 3.14, True]
list_to_remove = ['item', 5, 'foo']
final_list = list(set(item_list) - set(list_to_remove))
Would give you the following output:
final_list = [3.14, True]
Note: this will remove duplicates in your input list and the elements in the output can be in any order (because set
s don't preserve order). It also requires all elements in both of your lists to be hashable.