Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Use 'set' to find the different items in list

Tags:

python

compare

I need to compare two lists in Python, and I know about using the set command to find similar items, but is there a another command I could use that would automatically compare them, instead of having to code for it?

I would like to find the items that aren't in each one. Say list one is as follows:

[1, 2, 3, 4, 5, 6]  

and list two is:

[1, 2, 3, 4, 6] 

I want to find that 5 is missing from the list, hopefully by a command, but I do know how to loop through comparing.

like image 388
RPiAwesomeness Avatar asked Mar 16 '13 22:03

RPiAwesomeness


People also ask

How do I get unique values in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.

What does unique () do in Python?

unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.


2 Answers

The docs are a good place to start. Here are a couple examples that might help you determine how you want to compare your sets.

To find the intersection (items that are in both sets):

>>> a = set([1, 2, 3, 4, 5, 6]) >>> b = set([4, 5, 6, 7, 8, 9]) >>> a & b set([4, 5, 6]) 

To find the difference (items that only in one set):

>>> a = set([1, 2, 3, 4, 5, 6]) >>> b = set([4, 5, 6, 7, 8, 9]) >>> a - b set([1, 2, 3]) >>> b - a set([7, 8, 9]) 

To find the symmetric difference (items that are in one or the other, but not both):

>>> a = set([1, 2, 3, 4, 5, 6]) >>> b = set([4, 5, 6, 7, 8, 9]) >>> a ^ b set([1, 2, 3, 7, 8, 9]) 

Hope that helps.

like image 90
Seth Avatar answered Sep 30 '22 08:09

Seth


Looks like you need symmetric difference:

a = [1,2,3] b = [3,4,5]  print(set(a)^set(b))   >>> [1,2,4,5] 
like image 26
tifon Avatar answered Sep 30 '22 08:09

tifon