Find elements NOT in the intersection of two lists
Question:
So I know how to find the intersection of two lists by doing:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
But what is the best way to find all the elements that are not included in the intersection. My initial idea is to create a union of the two lists and then remove all the elements from the intersection from the union, as such:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> intersection = list(set(a) & set(b))
>>> union = list(set(a) | set(b))
>>> non_intersection = intersection - union
[2, 4, 6]
Is this the best way to do this or is there another way?
Answers:
Symmetric difference?
>>> set(a).symmetric_difference(b)
{2, 4, 6}
I usually prefer a shortcut:
set(a) ^ set(b)
{2, 4, 6}
So I know how to find the intersection of two lists by doing:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
But what is the best way to find all the elements that are not included in the intersection. My initial idea is to create a union of the two lists and then remove all the elements from the intersection from the union, as such:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> intersection = list(set(a) & set(b))
>>> union = list(set(a) | set(b))
>>> non_intersection = intersection - union
[2, 4, 6]
Is this the best way to do this or is there another way?
Symmetric difference?
>>> set(a).symmetric_difference(b)
{2, 4, 6}
I usually prefer a shortcut:
set(a) ^ set(b)
{2, 4, 6}