How can I compare two lists in python and return not matches

Just use a list comprehension:

def returnNotMatches(a, b):
    return [[x for x in a if x not in b], [x for x in b if x not in a]]

This should do

def returnNotMatches(a, b):
    a = set(a)
    b = set(b)
    return [list(b - a), list(a - b)]

And if you don't care that the result should be a list you could just skip the final casting.


One of the simplest and quickest is:

new_list = list(set(list1).difference(list2))

BONUS! If you want an intersection (return the matches):

new_list = list(set(list1).intersection(list2))

Tags:

Python