Home > database >  Mutually Exclusive Lists Python
Mutually Exclusive Lists Python

Time:08-11

I'm trying to simplify this code so it doesn't use two for loops. The aim is to end up with a list of numbers that exist in one list but not the other ie. mutually exclusive.

Here is the code:

list1 = [1, 1, 2, 4, 6, 6, 9]
list2 = [1, 2, 3, 5, 6, 7, 8]

def mutually_exclusive(list1,list2):
    new_list = []
    for x in list1:
        if x not in list2:
            new_list.append(x)
        else:
            pass
        
    for y in list2:
        if y not in list1:
            new_list.append(y)
        else:
            pass
    return new_list

mutually_exclusive(list1,list2)

and the desired result: [4, 9, 3, 5, 7, 8]

any help much appreciated thanks.

I have tried zip but doesn't yield all results.

CodePudding user response:

You could also do it like this:

list1 = [1, 1, 2, 4, 6, 6, 9]
list2 = [1, 2, 3, 5, 6, 7, 8]

def mutually_exclusive(list1,list2):
    return list(set(list1)^set(list2))

print(mutually_exclusive(list1, list2))

Result:

[3, 4, 5, 7, 8, 9]

CodePudding user response:

You can do the following using symmetric_difference:

l1 = [1, 1, 2, 4, 6, 6, 9]
l2 = [1, 2, 3, 5, 6, 7, 8]
list(set(l1).symmetric_difference(set(l2)))

In [7]: l1
Out[7]: [1, 1, 2, 4, 6, 6, 9]

In [8]: l2
Out[8]: [1, 2, 3, 5, 6, 7, 8]

In [9]: list(set(l1).symmetric_difference(set(l2)))
Out[9]: [3, 4, 5, 7, 8, 9]
  • Related