Sets

Sets are unordered collections with no duplicate members.

Initialization

set() # create an empty set
{1, 3} # {1, 3} create a set with elements

Methods

a = set('a')
a.add('b') # add b to set
a.clear() # remove all elements from set
a.copy() # return a shallow copy which is returned.

# check for membership
if 'b' in a:
    print(f"b is in the set")
a = set('abracadabra')
b = set('alacazam')
a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
a - b                              # letters in a but not in b
{'r', 'd', 'b'}
a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a & b                              # letters in both a and b
{'a', 'c'}
a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
x = {"a","b","c","d","e"}
y = {"c","d"}
x > y # return if x is a superset of y.
x < y # return if x is a subset of y