23

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

YXD
  • 31,741
  • 15
  • 75
  • 115
K00764
  • 233
  • 1
  • 2
  • 6
  • 3
    What should happen if they have the same elements, but in a different order? E.g. `[1, 2, 3]` and `[3, 2, 1]`? In other words, do you want pairwise comparison, or just that the set of elements is the same? – groundlar Mar 21 '14 at 13:06
  • 3
    `[x for x in b if x not in a]` – yuvi Mar 21 '14 at 13:17

2 Answers2

32

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

user4815162342
  • 141,790
  • 18
  • 296
  • 355
15

If the second set is not always a subset of the first then the difference operator '-' may not always return what you expect.

E.g.

[1,2,3,4,5] - [3,4,5,6,7] = [1,2]

If you want a set of items in either list but not both lists use the symmetric difference operator '^'.

[1,2,3,4,5] ^ [3,4,5,6,7] = [1,2,6,7]

The symmetric difference operator, assuming it does what you want, also has the advantage of being commutative. This means you don't need to determine in which order to compare the sets like you do with the difference operator.

http://docs.python.org/2/library/stdtypes.html#set

Dan Bechard
  • 5,104
  • 3
  • 34
  • 51