Set Operations In Python

Sets in Python is unordered collection of unique elements whereas list in Python is ordered list of colleciton which can contain duplicate elements.

Define Sets in Python

In [1]:
a = {200,100,10,20}
b = {10,30,40,38}

Another way is to use the keyword Set as shown below.

In [2]:
set([200,100,10,20])
Out[2]:
{10, 20, 100, 200}

Check if Set is Subset of another Set

In [3]:
a.issubset(b)
Out[3]:
False

Intersection of two Sets

In [4]:
a & b
Out[4]:
{10}

Union of two Sets

In [5]:
a | b
Out[5]:
{10, 20, 30, 38, 40, 100, 200}

Difference of two Sets

In [6]:
a - b
Out[6]:
{20, 100, 200}

Symmetric Difference of two Sets

The symmetric difference of two sets a and b is the set (a – b) Union (b – a).

In [7]:
a ^ b
Out[7]:
{20, 30, 38, 40, 100, 200}