Sets

Sets in python are same as sets in mathematics and Python allows you to perform operations such as union, intersection, Cartesian etc. A set can be created as follows:

name_set = {'Eric','Alex','Lisa','Richard'}
print(name_set)

You can create a set from a list as follows:

name_list = ['Eric','Alex','Lisa','Richard']
name_set = set(name_list)
print(name_set)

Union of two sets

Union is used to combine values of two sets into one set:

set1 = {1,2,3}
set2 = {4,5,6}
set3 = set1.union(set2)
print(set3)

Intersection of two sets

Intersection function delivers a set that has elements that were common in two sets:

set1 = {1,2,3,4}
set2 = {4,5,6}
set3 = set1.intersection(set2)
print(set3)

subset and superset

issubset() is a method that is used to find out whether a set is a subset of the other set or not. The function returns true if it is a subset or else false is returned.

set1 = {1,2,3,4,3,4,5,6,9,10}
set2 = {4,5,6}
if set2.issubset(set1):
print("set2 is a subset of set1")

issuperset() is a method that is used to find out whether a set is a superset of the other set or not. The function returns true if it is a superset or else false is returned.

set1 = {1,2,3,4,3,4,5,6,9,10}
set2 = {4,5,6}
if set1.issuperset(set2):
print("set1 is a superset of set2")
<<< Exception Handling in Python