0

So I have a list, let's say

a = [1, 2, 3, 4, 2, 1, 2, 4]

1 appears twice, 2 appears three times, 4 appears twice. Now I define

b = [4, 2, 2]

Now I want a new list, c, that has the entries of a that are not in b. I tried using list comprehension:

c = [x for x in a if x not in b]

However, this omits the entry if it is in b, rather than seeing how many of each entry are in b and removing that many from a.

c == [1, 3, 1]

I would want it to be

c == [1, 3, 1, 2, 4]

Can anyone provide some help?

J. Doe
  • 1

1 Answers1

4

You can loop through list b and remove each element from list a:

for i in b:
    a.remove(i)

a
# [1, 3, 1, 2, 4]
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 1
    Thank you! Asking the question made me think about this route and I came to the same conclusion. – J. Doe Dec 04 '16 at 00:54
  • Nice & simple answer! One thing of note is the O(n*m) complexity, which can be reduced to O(n + m) but not with such a clear, concise implementation. To do that you'd probably want to use a histogram via `collections.Counter`. – orip Dec 04 '16 at 00:58