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: Day 11: Sets, 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 ^.

Wrapping up

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? There's over 35 hours of material to keep you busy, along with quizzes, exercises, and several large projects!

We'd also really appreciate it if you signed up to our mailing list below. It's a great way to keep up to date with all our content, and we also regularly share discount codes for our courses, ensuring you get the best deals.