Reputation: 4483
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
had 2 occurrences in listA and once in listB, now it appears 2-1=1 times2
did not appear in listA, so nothing happens3
stays with 1 occurrence, as its not in listB5
occurred 3 times in listA and 2 in listB, so now it occurs 3-2=1 times7
occurred once in listA and once in listB, so now it will appear 1-1=0 timesDoes this make sense?
Upvotes: 2
Views: 2375
Reputation: 7798
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
Upvotes: 4
Reputation: 1425
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]
Upvotes: 3