Set & Frozenset

  • A set object is an unordered collection of immutable values, set type is mutable
  • Frozenset type is immutable

Set

In [ ]:
s = set(['a', 'a', 'b', 'c', 'd']); # {'b', 'a', 'd', 'c'}
s2 = set(['a', 'd', 'e', 'f']); # {'a', 'e', 'd', 'f'}

#access element
for e in s:
    print(e, end=' ')
print()

print(s|s2) #union, {'e', 'b', 'a', 'd', 'f', 'c'}
print(s&s2) #intersection, {'a', 'd'}
print(s-s2) #difference, {'b', 'c'}

s.add('g'); # {'g', 'b', 'a', 'd', 'c'}
s.remove('d'); #remove element; raise KeyError if not present
s.discard('c'); #remove if present
s.pop(); #remvoe an arbitrary element

print(s.issuperset(set(['b']))) # True
print(set(['b']).issubset(s)) # True

Frozenset

In [ ]:
s = frozenset(['a', 'a', 'b', 'c', 'd']); # {'b', 'a', 'd', 'c'}
s2 = frozenset(['a', 'd', 'e', 'f']); # {'a', 'e', 'd', 'f'}

print(s|s2) #union
print(s&s2) #intersection
print(s-s2) #difference

print(s.issuperset(frozenset(['b']))) # True
print(frozenset(['b']).issubset(s)) # True