symmetric_difference Output as Two Separate Lists

32 views Asked by At

Let's say we have two lists of values, whereby each list only contains unique values unto itself. There will never be duplicate values in a single list.

L1 | L2
-------
a  |  a
b  |  d
c  |  e
d  |  g
e  |  h
f  |  i
   |  j

We can get the differences of these lists using set(L1).symmetric_difference(L2), but unfortunately that lumps the results together in a single list. For example, the output of list(set(L1).symmetric_difference(L2)) is ['c', 'b', 'h', 'i', 'j', 'f', 'g'].

Is there a way to obtain two separate lists of output from list(set(L1).symmetric_difference(L2)) like ['c', 'b', 'f',] and ['h', 'i', 'j', 'g'] instead?

Or is there a way to obtain two separate lists as output while comparing the two sets/lists against each other only once?

1

There are 1 answers

4
Taher A. Ghaleb On

You can simply do the following:

dif_1_from_2 = list(set(L1) - set(L2))
dif_2_from_1  = list(set(L2) - set(L1))

And you can create a function to do that like this:

def get_symmetric_difference(L1, L2):
    return list(set(L1)-set(L2)), list(set(L2)-set(L1))

and then you call it like this:

print(get_symmetric_difference(L1, L2))

Hope this helps.