Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I would like to return values from both lists that not in the other one:

bar = [ 1,2,3,4,5 ]
foo = [ 1,2,3,6 ]

returnNotMatches( a,b )

would return

[[ 4,5 ],[ 6 ]]
like image 720
TheTask1337 Avatar asked Mar 01 '16 01:03

TheTask1337


People also ask

Can 2 lists be compared in Python?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do I compare two lists and differences in Python?

Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.


1 Answers

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))
like image 112
jvel07 Avatar answered Oct 02 '22 16:10

jvel07