Behseini
Behseini

Reputation: 6330

Getting differences between two lists (not just comparison)

The following code is listing the difference between two lists:

def Diff(li1, li2):
    return list(set(li1) - set(li2)) + list(set(li2) - set(li1))

ListA = ["A","B","C","D","E"];
ListB= ["A","B","X"];

diff = Diff(ListA , ListB)
print(diff )

Output

['D', 'E', 'C', 'X']

but what I need is not just listing the differences, what I need is:

A) list only Items from List A where are not listed in List B
B) list only Items from List B where are not listed in List A

How can I do this?

Upvotes: 0

Views: 170

Answers (2)

Alain T.
Alain T.

Reputation: 42143

If your lists can contain duplicate elements, you will need to use Counter instead of set:

from collections import Counter
def diff(L1,L2):
    C1,C2 = Counter(L1),Counter(L2)
    return list((C1-C2).elements()), list((C2-C1).elements())

Output:

ListA = ["A","B","C","D","E"]
ListB= ["A","B","X"]

print(diff(ListA ,ListB))

(['C', 'D', 'E'], ['X'])   # (Only in listA, Only in ListB)

ListA = ["A","B","B","B","C","D","E"]
ListB= ["A","A","X","B","C","C","C"]

print(diff(ListA ,ListB))

(['B', 'B', 'D', 'E'], ['A', 'X', 'C', 'C'])

If you only need a single list of elements that are not in both lists:

With Counter to support duplicates:

def diff(L1,L2):
    C1,C2 = Counter(L1),Counter(L2)
    return [*((C1|C2)-(C1&C2)).elements() ]

# ['C', 'D', 'E', 'X']
# ['A', 'B', 'B', 'C', 'C', 'D', 'E', 'X']

Using sets if lists don't contain duplicates:

def diff(L1,L2):
    return set(L1).symmetric_difference(L2)

# {'D', 'X', 'E', 'C'}

Upvotes: 0

omar nofal
omar nofal

Reputation: 36

your code list what you need but in one list

A) list only Items from List A where are not listed in List B

InANotInB=list(set(li1) - set(li2))

B) list only Items from List B where are not listed in List A

InBNotInA=list(set(li2) - set(li1))

Upvotes: 2

Related Questions