Opposite of set.intersection in python?

Question:

In Python you can use a.intersection(b) to find the items common to both sets.

Is there a way to do the disjoint opposite version of this? Items that are not common to both a and b; the unique items in a unioned with the unique items in b?

Asked By: user4847061

||

Answers:

You are looking for the symmetric difference; all elements that appear only in set a or in set b, but not both:

a.symmetric_difference(b)

From the set.symmetric_difference() method documentation:

Return a new set with elements in either the set or other but not both.

You can use the ^ operator too, if both a and b are sets:

a ^ b

while set.symmetric_difference() takes any iterable for the other argument.

The output is the equivalent of (a | b) - (a & b), the union of both sets minus the intersection of both sets.

Producing the output takes O(M+N) time for sets of length M and N, respectively; M steps to copy set a then N steps to alter that set based on each value in b:

def symmetric_difference(a, b):
    result = set(a)
    for elem in b:
        try:
            result.remove(elem)
        except KeyError:
            result.add(elem)
    return result

There are in-place variants too, where set a is altered directly; use a.symmetric_difference_update(b) or a ^= b. The in-place variant takes O(N) time, so it depends on the size of set b only:

def symmetric_difference_update(a, b):
    for elem in b:
        try:
            a.remove(elem)
        except KeyError:
            a.add(elem)
    # no return, a has been updated in-place
Answered By: Martijn Pieters

Try this code for (set(a) – intersection(a&b))

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

for i in b:
   if i in a:
      a.remove(i)

print(a)

the output is [1,4,5,6]
I hope, it will work

a={1,2,4,5,6}
b={5,6,4,9}
c=(a^b)&b
print(c) # you got {9}
Answered By: Kaung Yar Zar

e, f are two list you want to check disjoint

a = [1,2,3,4]
b = [8,7,9,2,1]

c = []
def loop_to_check(e,f):
    for i in range(len(e)):
        if e[i] not in f:
            c.append(e[i])


loop_to_check(a,b)
loop_to_check(b,a)
print(c)

## output is [3,4,8,7,9]

This loops around to list and returns the disjoint list

Answered By: buda__

The best way is a list comprehension.

a = [ 1,2,3,4]
b = [ 8,7,9,2,1]
c = [ element for element in a if element not in b] 
d = [ element for element in b if element not in a] 
print(c) 
# output is [ 3,4]
print(d) 
# output is  [8,7,9]

You can join both lists

Answered By: Apeasant
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.