I have two lists in Python:
JavaScript
x
3
1
temp1 = ['One', 'Two', 'Three', 'Four']
2
temp2 = ['One', 'Two']
3
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:
JavaScript
1
2
1
temp3 = ['Three', 'Four']
2
Are there any fast ways without cycles and checking?
Advertisement
Answer
To get elements which are in temp1
but not in temp2
(assuming uniqueness of the elements in each list):
JavaScript
1
3
1
In [5]: list(set(temp1) - set(temp2))
2
Out[5]: ['Four', 'Three']
3
Beware that it is asymmetric :
JavaScript
1
3
1
In [5]: set([1, 2]) - set([2, 3])
2
Out[5]: set([1])
3
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]))
.