Skip to content

Sets

Set {}

Sets are unordered collections of unique objects. Set object does not support indexing. Sets are very useful when having two sets and comparing them to each other.

my_set = {1, 2, 3, 4, 5}  # There's no duplicates, Everything has to be unique.
my_set.add(100)
my_set.add(2)
print(my_set)             # 2 does'nt get added

print(5 in my_set)        # to check if something exists in set
print(len(my_set))        # length of set
print(list(my_set))       # converts set into list

new_set = my_set.copy()  # copies the set in new variable
print(new_set)

print(my_set.clear())  # clears the set

Comparision in sets

set1 = {1, 2, 3, 4, 5}  
set2 = {4, 5, 6, 7, 8, 9}  


print(set1.isdisjoint(set2))        # checks if they have uncommom values
print(set1.issubset(set2))          # the entirety of one set is inside of the other set
print(set1.issuperset(set2))        # set1 encompasses everything that of set2
print(set1.union(set2))             # unites both the sets together
print(set1 | (set2))                # works like union

print(set1.intersection(set2))      # shows common values [|]
print(set1.difference(set2))        # shows different values of set1

print(set1.difference_update(set2)) # modifies the set by keeping only different values
print(set1.discard(5))              # discards the value 5