HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonCriticalCanonical

Get difference between two lists with Unique Entries

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withuniquebetweenlistsentriesdifferencetwoget

Problem

I have two lists in Python:

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']


Assuming the elements in each list are unique, I want to create a third list with items from the first list which are not in the second list:

temp3 = ['Three', 'Four']


Are there any fast ways without cycles and checking?

Solution

To get elements which are in temp1 but not in temp2 (assuming uniqueness of the elements in each list):

In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']


Beware that it is asymmetric :

In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])


where you might expect/want it to equal set([1, 3]). If you do want set([1, 3]) as your answer, you can use set([1, 2]).symmetric_difference(set([2, 3])).

Code Snippets

In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']
In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])

Context

Stack Overflow Q#3462143, score: 1822

Revisions (0)

No revisions yet.