I have two lists in Python, like these:
temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']
I need to create a third
If you run into TypeError: unhashable type: 'list'
you need to turn lists or sets into tuples, e.g.
set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
See also How to compare a list of lists/sets in python?
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']
Beware that
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'll need to use set([1, 2]).symmetric_difference(set([2, 3]))
.
i'll toss in since none of the present solutions yield a tuple:
temp3 = tuple(set(temp1) - set(temp2))
alternatively:
#edited using @Mark Byers idea. If you accept this one as answer, just accept his instead.
temp3 = tuple(x for x in temp1 if x not in set(temp2))
Like the other non-tuple yielding answers in this direction, it preserves order
Here are a few simple, order-preserving ways of diffing two lists of strings.
Code
An unusual approach using pathlib:
import pathlib
temp1 = ["One", "Two", "Three", "Four"]
temp2 = ["One", "Two"]
p = pathlib.Path(*temp1)
r = p.relative_to(*temp2)
list(r.parts)
# ['Three', 'Four']
This assumes both lists contain strings with equivalent beginnings. See the docs for more details. Note, it is not particularly fast compared to set operations.
A straight-forward implementation using itertools.zip_longest:
import itertools as it
[x for x, y in it.zip_longest(temp1, temp2) if x != y]
# ['Three', 'Four']
Try this:
temp3 = set(temp1) - set(temp2)
(list(set(a)-set(b))+list(set(b)-set(a)))