Welcome to another Python snippet post. Today I'm going to be talking about a lesser known set operation called symmetric difference. If you're not very familiar with sets, you might want to check out our earlier posts on this topic: Collections in Python, Set Operators.

One thing many students don't realise about the difference method is that it produces different output for the same two sets, depending on which set you called the method on.

s1 = {1, 3, 4, 5, 7, 8}
s2 = {2, 3, 4, 6, 8, 9}

print(s1.difference(s2))  # {1, 5, 7}
print(s2.difference(s1))  # {9, 2, 6}

The same is true when using the - operator, instead of the method syntax.

symmetric_difference is different, and actually works very much how most people expect difference to work. symmetric_difference returns every value which does not feature in both collections.

For sets s1 and s2, the symmetric difference of s1 and s2 is equivalent to the union of s1.difference(s2) and s2.difference(s1).

s1 = {1, 3, 4, 5, 7, 8}
s2 = {2, 3, 4, 6, 8, 9}

s3 = s1.symmetric_difference(s2)
s4 = s1.difference(s2) | s2.difference(s1)

print(s3)  # {1, 2, 5, 6, 7, 9}
print(s4)  # {1, 2, 5, 6, 7, 9}

For those of you who like to use the set operators rather than the method syntax, the operator for symmetric difference is ^.

Hopefully you learnt something new, and be sure to check back next week for another Python snippet! If you can't wait, why not check out our Complete Python Course? If you follow the link in this post, you can get lifetime access for just $9.99, and there's also a 30 day money back guarantee. Hopefully we'll see you there!