Remove multiple values from 2 lists, but only once, in Python

Viewed 83

I have two lists:

A = [5,5,4,3]
B = [5,1]

I want to remove values that appear in both lists, but only once, i.e. output should be:

Aprime = [5,4,3]
Bprime = [1]

I understand that a good way to get the difference is with sets, but this removes all repeats, not just once

3 Answers

You can create collections.Counter objects with the input lists and obtain the differences of the two:

from collections import Counter
a = Counter(A)
b = Counter(B)
Aprime = list((a - b).elements()) # Aprime becomes: [5, 4, 3]
Bprime = list((b - a).elements()) # Bprime becomes: [1]

Use sets to find the duplicates, but then remove them once from the original lists.

dups = set(A).intersection(set(B))
for dup in dups:
    A.remove(dup)
    B.remove(dup)

You can remove from each of the counters associate to A and B the Counter build using the set of the two lists so that they are only considered once.

>>> A = [5,5,5,1,1]
>>> B = [5,1,1]
>>> a_new = list((Counter(A) - Counter(set(B))).elements())
>>> b_new = list((Counter(B) - Counter(set(A))).elements())
>>> a_new
[5, 5, 1]
>>> b_new
[1]
Related