python find difference between two lists

K00764 picture K00764 · Mar 21, 2014 · Viewed 47k times · Source

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. :)

Answer

user4815162342 picture user4815162342 · Mar 21, 2014

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]).