Python: Set Comparisons

1. Set Membership Check

In set we can check if the element exist in the set or not.

Example:

set_1 = {1,2,3,4,5}
print(1 in set_1)
print(5 not in set_1)

Output:

True
False

2. Set Equivalent Check

We use this operation to check whether two sets are equivalent to each other or not.

Example:

set_1 = {1,2,3,4,5}
set_2 = {1,2,3,4,5}

print(set_1 == set_2)
print(set_1 != set_2)

Output:

True
True

3. Subset Check

A subset is a set that entirely exists within another. We use this operator to check whether S1 is the subset of S2 or not.

Example:

set_1 = {1,2,3,4}
set_2 = {3,4,5,6}
print(set_1.issubset(set_2))

Output: False

4. Superset Check

A superset is the opposite of a subset. A set is declared as a superset if all elements of the another set exist within it.

Example:

set_1 = {1,2,3,4}
set_2 = {3,4}
print(set_1.issuperset(set_2))

Output: True

Tags