Python Working With Frozenset Data Type

Python Working With Frozenset Data Type

Frozenset is an immutable unordered collection of unique elements. It holds collection of element but it does not guarantee the order of the elements in it. As it is immutable we cannot able to update the data once created. when we need to get a unique elements out of group of the repeated elements then we can simply use built-in function **"frozenset". **we can also use the set but we should only use it when we want to update it afterwards. Because it consumes more memory than frozenset.

working with frozenset data type in python

  • Convert a group of repeated list elements into a set of non repeated elements
s = [1,2,3,"hi",1,2,3,5,8,"hi","hello","google"]
output = frozenset(s)
print(output)
# Output: frozenset({1, 2, 3, 'google', 5, 8, 'hi', 'hello'})
  • Copy one set S1 into another set S2
s = frozenset((1,2,4,5,7))
output = s.copy()
print(output)
# Output: frozenset({1, 2, 4, 5, 7})

Return a shallow copy of a set.

  • Find the set difference between set S1 and set S2

s1 = frozenset((1,2,4,5,7))
s2 = frozenset((4,5,7))
output = s1.difference(s2) # s1 - s2
print(output)
# Output: frozenset({1, 2})
Returns all elements that are in this set but not the others.

  • Find if set S1 is disjoint of set S2

s1 = frozenset((1,2,4,5,7))
s2 = frozenset((4,5,7))
output = s1.isdisjoint(s2)
print(output)
# Output: False
s1 = frozenset((1,2,3,"a"))
s2 = frozenset((4,5,7))
output = s1.isdisjoint(s2)
print(output)
# Output: True
Return True if two sets have a null intersection.

  • Find if set S1 is superset of set S2

s1 = frozenset((1,2,4,5,7))
s2 = frozenset((4,5,7))
output = s1.issuperset(s2)
print(output)
# Output: False
s1 = frozenset((1,2,3,"a", 5, 4))
s2 = frozenset((4,5))
output = s1.issuperset(s2)
print(output)
# Output: True
Report whether this set contains another set.

  • Find if set S1 is subset of S2
s1 = frozenset((4,5,7))
s2 = frozenset((1,2,4,5,7))
output = s1.issubset(s2)
print(output)
# Output: True
s1 = frozenset((1,2,3,"a", 5, 4))
s2 = frozenset((4,5))
output = s1.issubset(s2)
print(output)
# Output: False

Report whether another set contains this set.

  • Find union of set S1 and set S2
s1 = frozenset((4,5,7))
s2 = frozenset((1,2,4,5,7))
output = s1.union(s2)
print(output)
# Output: frozenset({1, 2, 4, 5, 7})

Returns all elements that are in either set

  • Find Symmetric difference of set S1 and set S2

s1 = frozenset((4,5,7))
s2 = frozenset((1,2,4,5,7))
output = s1.symmetric_difference(s2)
print(output)
# Output: frozenset({1, 2})
Returns all elements that are in exactly one of the sets

Reference: * https://docs.python.org/3/library/stdtypes.html#frozenset * https://en.wikipedia.org/wiki/Set_theory