Python frozensets

  • A frozenset is an unordered collection of unique and hashable objects.
  • So, lists and dictionaries cannot be members of a frozenset.
  • A tuple can be a member if and only if all its members are immutable.
  • A frozenset is immutable and hashable.
  • A frozenset has to be created using the frozenset() function.

create a frozenset

students = ["John", "Anji", "Charles"]
students_set = frozenset(students)
print(type(students_set))
# Output: <class 'frozenset'>
print(students_set)
# Output: frozenset({'Anji', 'John', 'Charles'})

elements are unique

numbers = (1,2,3,4,1,2,6,8,9,10)
unique_numbers = frozenset(numbers)
print(unique_numbers)
# Output: frozenset({1, 2, 3, 4, 6, 8, 9, 10})

convert string to a frozenset

string = "Python is awesome"
fset = frozenset(string)
print(fset)
# Output: frozenset({'a', 'w', 't', 'o', 'h', 'i', 'e', 'P', ' ', 'n', 's', 'y', 'm'})

find set difference

mammals = frozenset(["Lion", "Deer", "Bat"])
fliers = frozenset(["Parrot", "Eagle", "Bat"])

diff = mammals - fliers
print(diff)
# Output: frozenset({'Lion', 'Deer'})

print(mammals.difference(fliers))
# Output: frozenset({'Lion', 'Deer'})

find set symmetric difference

mammals = frozenset(["Lion", "Deer", "Bat"])
fliers = frozenset(["Parrot", "Eagle", "Bat"])

diff = mammals ^ fliers
print(diff)
# Output: frozenset({'Deer', 'Eagle', 'Lion', 'Parrot'})

print(mammals.symmetric_difference(fliers))
# Output: frozenset({'Deer', 'Eagle', 'Lion', 'Parrot'})

find union of sets

mammals = frozenset(["Lion", "Deer", "Bat"])
fliers = frozenset(["Parrot", "Eagle", "Bat"])

union = mammals | fliers
print(union)
# Output: frozenset({'Lion', 'Deer', 'Bat', 'Eagle', 'Parrot'})

print(mammals.union(fliers))
# Output: frozenset({'Lion', 'Deer', 'Bat', 'Eagle', 'Parrot'})

find intersection of sets

mammals = frozenset(["Lion", "Deer", "Bat"])
fliers = frozenset(["Parrot", "Eagle", "Bat"])

common = mammals & fliers
print(common)
# Output: frozenset({'Bat'})

print(mammals.intersection(fliers))
# Output: frozenset({'Bat'})

check if sets are disjoint

mammals = frozenset(["Lion", "Deer"])
fliers = frozenset(["Parrot", "Eagle", "Bat"])

is_disjoint = mammals.isdisjoint(fliers)
print(is_disjoint)
# Output: True

check if set is subset of another set

s1 = frozenset([1,2,3,4,5,6,7,8])
s2 = frozenset([1,2])

print(s2.issubset(s1))
# Output: True

check if set is superset of another set

s1 = frozenset([1,2,3,4,5,6,7,8])
s2 = frozenset([1,2])

print(s1.issuperset(s2))
# Output: True

Note: union, intersection, difference, symmetric_difference, issubset, issuperset methods will accept any iterable as an argument.

using in and not in with fronzensets

presidents = frozenset([
    "Rajendra Prasad",
    "Sarvepalli Radhakrishnan",
    "Zakir Husain",
    "V. V. Giri",
    "Fakhruddin Ali Ahmed",
    "Neelam Sanjiva Reddy"
])

print("Anji" in presidents)
# Output: False

print("Anji" not in presidents)
# Output: True

References