How to Find the Symmetric Difference Between Two Lists in Python
In Python, there is no method or function to find the union of items items in two lists. The symmetric difference between two lists refer to the items which are in the first list, but not in the other, plus the items in the second list but not in the first. It is basically the union of both lists minus the intersection. This blog post will show you how to do it.
Create two lists a
and b
For our example, we will create lists a
and b
having a few common items and a few different items.
a = ['apple', 'orange', 'mango', 'strawberry', 'papaya', 'banana']
b = ['durian', 'apple', 'orange', 'mango', 'papaya', 'banana']
Find the symmetric difference between the lists using set()
and ^
There are no list functions to find the symmetric difference of two lists, but there is a set operator ^
that can be used. You can convert the lists to sets and perform the ^
operator between the sets.
We will create list c
which contains the symmetric difference of set(a)
and set(b)
Symmetric difference of a
and b
c = list(set(a) ^ set(b))
print(c)
Output:
['strawberry', 'durian']
Full Python code
a = ['apple', 'orange', 'mango', 'strawberry', 'papaya', 'banana']
b = ['durian', 'apple', 'orange', 'mango', 'papaya', 'banana']
c = list(set(a) ^ set(b))
print(c)
Output:
['strawberry', 'durian']
Why is the resulting list c
not ordered?
The set()
function does not retain the order. Every time you create a set from a list, or from anything, the items in the set can appear anywhere randomly.
Set operations
This is a list of all set operations, for reference.
List Operation | Python | Blog Post |
---|---|---|
common items in lists | set(a) & set(b) |
find common items |
difference between lists | set(a) - set(b) |
find difference |
symmetric difference between lists | set(a) ^ set(b) |
find symmetric difference |
union of lists | set(a) | set(b) |
find union |
Conclusion
If you found this blog post useful, feel free to share it. Thanks for reading.
Related Posts
If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.