1

I have three lists:
a = [1, 2, 3, 4] b = [2, 3, 4, 5] c = [3, 4, 5, 6]

My goal is to get all values which are not present in all of the three lists: [1,2,5,6]
Basically I am searching the "negation" of set(a) & set(b) & set(c).

An efficient solution would be appreciated since the lists are very long.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • 1
    Possible duplicate of [Opposite of set.intersection in python?](https://stackoverflow.com/questions/29947844/opposite-of-set-intersection-in-python) – Chris_Rands Mar 05 '19 at 15:30
  • @Chris_Rands this is not really a duplicate. One can not easily use the `set.symmetric_difference` method with three sets – kalehmann Mar 05 '19 at 15:40
  • @kalehmann The accepted answer say "The output is the equivalent of (a | b) - (a & b), the union of both sets minus the intersection of both sets."-- it is a clear dupe i think- add your answer to the duplicate if you want – Chris_Rands Mar 05 '19 at 15:41
  • @Chris_Rands: I will keep my answer because I also added the numpy example for faster computation, but link to your comment and the original question – kalehmann Mar 05 '19 at 15:42
  • 1
    @NickA this does not work. `a ^ b` is `{1, 5}`. The difference to c contains now also a 4 – kalehmann Mar 05 '19 at 15:44
  • 1
    No problem, this was also my first idea :) – kalehmann Mar 05 '19 at 15:46

1 Answers1

3

The opposite of set(a) & set(b) & set(c) is already explained in this question as stated by Chris_Rands in the comments:

>>> (set(a) | set(b) | set(c)) - (set(a) & set(b) & set(c))
{1, 2, 5, 6}

For really long lists, using numpy should be may efficient:

import numpy as np
from functools import reduce

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

union = reduce(numpy.union1d, (a,b,c))
intersect = reduce(numpy.intersect1d, (a,b,c))
print(numpy.setdiff1d(union, intersect))

Output:

[1 2 5 6]
kalehmann
  • 4,821
  • 6
  • 26
  • 36