Sets (Mengen)
Setze {}
Sets sind ungeordnete Sammlungen einzigartiger Objekte. Das festgelegte Objekt unterstützt keine Indizierung. Sets sind sehr nützlich, wenn man zwei Sets hat und sie miteinander vergleicht.
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
Vergleich in Mengen
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