Typical set operations

We typically perform below operations on set. These are typical mathematical set operations that can be performed in Python.

  • union - get all unique elements from 2 or more sets.

  • intersection - get common elements between 2 or more sets.

  • difference - get operations from one set but not in other set.

All the above functions generate a new set.

s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6, 7}
s1.union(s2)
{1, 2, 3, 4, 5, 6, 7}
s1.intersection(s2)
{3, 4}
s1.difference(s2)
{1, 2}
s2.difference(s1)
{5, 6, 7}