38

I need to compare two lists in Python, and I know about using the set command to find similar items, but is there a another command I could use that would automatically compare them, instead of having to code for it?

I would like to find the items that aren't in each one. Say list one is as follows:

[1, 2, 3, 4, 5, 6] 

and list two is:

[1, 2, 3, 4, 6]

I want to find that 5 is missing from the list, hopefully by a command, but I do know how to loop through comparing.

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
RPiAwesomeness
  • 5,009
  • 10
  • 34
  • 52
  • 6
    What do you need to compare? Do you need to find the matching items? What exactly do you need to do? – Josh Smeaton Mar 16 '13 at 23:01
  • 4
    Ugh, no need to vote to close yet. Give OP a chance to modify the question and provide context. – Josh Smeaton Mar 16 '13 at 23:03
  • I mean I would like to find the items that _aren't_ in each one. Say list one is as follows: [1, 2, 3, 4, 5, 6] and list two is: [1, 2, 3, 4, 6]. I want to find that 5 is missing from the list, hopefully by a command, but I do know how to loop through comparing – RPiAwesomeness Mar 16 '13 at 23:07

3 Answers3

62

The docs are a good place to start. Here are a couple examples that might help you determine how you want to compare your sets.

To find the intersection (items that are in both sets):

>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a & b
set([4, 5, 6])

To find the difference (items that only in one set):

>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a - b
set([1, 2, 3])
>>> b - a
set([7, 8, 9])

To find the symmetric difference (items that are in one or the other, but not both):

>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a ^ b
set([1, 2, 3, 7, 8, 9])
Seth
  • 45,033
  • 10
  • 85
  • 120
  • Would the finding the difference example work if lists a and b had thousands of elements? Basically is it a workable solution to deal with scaling later on? – Gcap Mar 03 '19 at 20:30
38

Looks like you need symmetric difference:

a = [1,2,3]
b = [3,4,5]

print(set(a)^set(b))


>>> [1,2,4,5]
tifon
  • 396
  • 3
  • 4
5

A simple list comprehension

In [1]: a=[1, 2, 3, 4, 5, 6] 

In [2]: b=[1, 2, 3, 4, 6]

In [3]: [i for i in a if i not in b]
Out[3]: [5]
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130