Python sets: difference() vs symmetric_difference()

Anya Samadi picture Anya Samadi · Jun 15, 2018 · Viewed 16.5k times · Source

What is the difference between difference() and symmetric_difference() methods in python sets?

Answer

timgeb picture timgeb · Jun 15, 2018

symmetric difference

If A and B are sets

A - B

is everything in A that's not in B.

>>> A = {1,2,3}
>>> B = {1,4,5}
>>> 
>>> A - B
{2, 3}
>>> B - A
{4, 5}

A.symmetric_difference(B) are all the elements that are in exactly one set, i.e. the union of A - B and B - A.

>>> A.symmetric_difference(B)
{2, 3, 4, 5}
>>> (A - B).union(B - A)
{2, 3, 4, 5}