2

Related to: Remove all the elements that occur in one list from another

I have listA [1, 1, 3, 5, 5, 5, 7] and listB [1, 2, 5, 5, 7] and I want to subtract occurrences of items from listA. The result should be a new list: [1, 3, 5] Note:

  1. 1 had 2 occurrences in listA and once in listB, now it appears 2-1=1 times
  2. 2 did not appear in listA, so nothing happens
  3. 3 stays with 1 occurrence, as its not in listB
  4. 5 occurred 3 times in listA and 2 in listB, so now it occurs 3-2=1 times
  5. 7 occurred once in listA and once in listB, so now it will appear 1-1=0 times

Does this make sense?

Community
  • 1
  • 1
ihadanny
  • 4,377
  • 7
  • 45
  • 76

2 Answers2

4

Here is a non list comprehension version for those new to Python

listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
for i in listB:
    if i in listA:
        listA.remove(i)

print listA
Skam
  • 7,298
  • 4
  • 22
  • 31
3

In cases like these a list comprehension should always be used:

listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]

newList = [i for i in listA if i not in listB or listB.remove(i)]

print (newList)

Here are the results:

[1, 3, 5]

Jossie Calderon
  • 1,393
  • 12
  • 21
  • Side effects aren't generally used with list comprehensions. The @Dart answer is more straightforward and doesn't have the possibly undesired side effect of modifying `listB`. The OP only wanted items removed from `listA`. This didn't remove items from `listA`, but generated a new list. – Mark Tolonen Jul 23 '16 at 17:23
  • @MarkTolonen Great remark. If the OP specified what he/she wanted as the output, I can attune my answer to that. – Jossie Calderon Jul 23 '16 at 17:31
  • thanks - that's exactly what I meant. @see-dart solution's is straight-forward, but I was looking for this kind of one-liner – ihadanny Jul 23 '16 at 18:01
  • brilliant and fast - couldn't find anything like this answer elsewhere – martino Mar 24 '20 at 09:45