Home > Software design >  remove elements of one list from another list python
remove elements of one list from another list python

Time:06-12

Is there a pythonic way to remove elements from one list to another list? (Not removing all duplicates)

For example, given [1, 2, 2, 3, 3, 3] (original list) and [1, 2, 3] (elements to be removed). It will return [2, 3, 3] We can assume that the two given lists are always valid. Elements in the "to be removed" list will be in the original list.

Thanks!

CodePudding user response:

I would use a counter of the elements to be removed.

So, something like

from collections import Counter 

data = [1, 2, 2, 3, 3, 3]
to_be_removed = [1, 2, 3, 3] # notice the extra 3

counts = Counter(to_be_removed)

new_data = []
for x in data:
    if counts[x]:
        counts[x] -= 1
    else:
        new_data.append(x)

print(new_data)

This solution is linear time / space. If you actually need to modify the list (which is code-smell, IMO), you would require quadratic time

Note, consider if you actually just want a multiset - i.e. you could just be working with counters all along, consider:

>>> Counter(data) - Counter(to_be_removed)
Counter({2: 1, 3: 1})

CodePudding user response:

This shoud work


original  = [1, 2, 2, 3, 3, 3] 
remove = [1, 2, 3] 

for i, x in enumerate(original):
    if x in remove:
        original.pop(i)

print(original)
  • Related