Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements NOT in the intersection of two lists

Tags:

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?

like image 914
Phillip Avatar asked Oct 21 '16 20:10

Phillip


People also ask

How do you find the uncommon element of two lists?

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.

How do you find the uncommon element between two lists in python?

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.

How do you check if a common element is in two lists in python?

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.


Video Answer


1 Answers

I usually prefer a shortcut:

set(a) ^ set(b) {2, 4, 6} 
like image 69
Gena Kukartsev Avatar answered Oct 05 '22 23:10

Gena Kukartsev