Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python find difference between two lists [duplicate]

Tags:

python

list

match

I am new to programming but I keep learning, and recently I hit the wall so I'm asking for help. Sorry if this was discussed before, but I can't find answer to my problem. I have two lists. And I need to compare them, and in the result to get the objects that DON'T match. For example:

a = [1,2,3,4,5,6]
b = [1,2,3,4,5,6,7,8,9]
result = [7,8,9].

And I only seem to find code and examples that return matches. Which I don't need.

Lists are in file notepad file.txt for you folks to keep in mind if you this helps you to help me. :)

like image 345
K00764 Avatar asked Mar 21 '14 13:03

K00764


People also ask

How do I compare two lists for duplicates 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 you find the difference between two lists in Python?

difference() to get the difference between two lists. Use set() to convert both lists into sets. Use set. difference(s) where set is the first set and s is the second set to get the difference between both sets.

How do I compare the contents of two lists in Python?

The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.

How do you find the symmetric difference of two lists in Python?

To get the symmetric difference between two lists in Python: Convert the lists to sets. Use the built-in symmetric_difference() function of sets to get the symmetric difference. Convert the result back to a list.


1 Answers

You can convert the lists to sets and run the usual set operations such as difference or symmetric difference. For example, set(b) - set(a) evaluates to set([7, 8, 9]).

like image 112
user4815162342 Avatar answered Oct 07 '22 19:10

user4815162342