Given sequences seq1
and seq2
, you can calculate the symmetric difference with
set(seq1).symmetric_difference(seq2)
For example,
In [19]: set([1,2,5]).symmetric_difference([1,2,9,4,8,9])
Out[19]: {4, 5, 8, 9}
Tip: Generating the set with the smaller list is generally faster:
In [29]: %timeit set(range(60)).symmetric_difference(range(600))
10000 loops, best of 3: 25.7 µs per loop
In [30]: %timeit set(range(600)).symmetric_difference(range(60))
10000 loops, best of 3: 41.5 µs per loop
The reason why you may want to use symmetric difference
instead of ^
(despite the beauty of its syntax) is because the symmetric difference
method can take a list as input. ^
requires both inputs be sets. Converting both lists into sets is a little more computation than is minimally required.
This question has been marked of as a duplicate of this question That question, however, is seeking a solution to this problem without using sets.
The accepted solution,
[a for a in list1+list2 if (a not in list1) or (a not in list2)]
is not the recommended way to XOR two lists if sets are allowed. For one thing, it's over 100 times slower:
In [93]: list1, list2 = range(600), range(60)
In [94]: %timeit [a for a in list1+list2 if (a not in list1) or (a not in list2)]
100 loops, best of 3: 3.35 ms per loop