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?
To get the common & uncommon elements in any two lists in python, we need to use python set. Now by using set utility functions, we can get the common & unique(uncommon) items in both the input lists.
Method 2 : Using set() + map() and ^ Firstly converting inner lists to tuples using map, and outer lists to set, use of ^ operator can perform the set symmetric difference and hence perform this task.
Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.
I usually prefer a shortcut:
set(a) ^ set(b) {2, 4, 6}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With