Search code examples
pythonlistsetlist-comprehensionlist-comparison

Remove items from a list if it is in another list while keeping the duplicate - Python


How to remove items from a list if it is in another list while keeping the duplicate?

I've succeeded by doing this but is there a faster way?

x = [1,2,3,4,7,7,5,6,7,8,8]
y = [1,4,5,6,8,9]
z = []
for i in x:
  if i not in y:
   z.append(i)
print z

Correct output:

[2, 3, 7, 7, 7]

Alternatively, a list comprehension also works but are these the only way?

x = [1,2,3,4,7,7,5,6,7,8,8]
y = [1,4,5,6,8,9]
z = [i for i in x if not in y]

Although using set is a lot faster but it doesn't keep the duplicate:

x = [1,2,3,4,7,7,5,6,7,8,8]
y = [1,4,5,6,8,9]
print list(set(x) - set(y))

The set subtraction gave the output that loses the duplicate:

[2, 3, 7]

Solution

  • If order isn't important

    >>> x = [1,2,3,4,7,7,5,6,7,8,8]
    >>> y = [1,4,5,6,8,9]
    >>> from collections import Counter
    >>> count=Counter(x)
    >>> for i in y:
    ...     del count[i]
    ... 
    >>> list(count.elements())
    [2, 3, 7, 7, 7]