frozenset in Python with Example

In contrast to set, frozenset is immutable or unchangeable. We use frozenset when we need to create an iterable-like set but with immutable properties.

Note: The frozenset type is equal to the set type in Python, except that it is immutable, whereas set is mutable.

Let's create a program that creates a frozenset type object named fs and prints its type using the type function:

x = [12, 43, 5, 64]
fs = frozenset(x)
print(type(fs))

The output should be:

Because the frozenset type object is immutable, let's create a program to demonstrate this property by changing the element:

x = [12, 43, 5, 64, 32, 55]

fs = frozenset(x)
print(fs)

fs[2] = 400
print(fs)

The image below displays an example of the output this Python program produced:

python frozenset

That is, the code, fs[2] = 400 raised an exception named TypeError, saying that the object frozenset does not support item assignment. The exception can be caught using the try-except block, as shown in the program given below:

x = [12, 43, 5, 64, 32, 55]

fs = frozenset(x)
print(fs)

try:
    fs[2] = 400
    print(fs)
except TypeError:
    print("\nThe frozenset type object does not allow item assignment")

Now the output should be:

frozenset({64, 32, 5, 43, 12, 55})

The frozenset type object does not allow item assignment

Because the frozenset type is immutable, we can use its items as keys in a dictionary or for any other purpose that the program requires.

Advantages of frozenset in Python

  • Immutability: "Frozenset" is immutable, which means that once it has been created, its elements cannot be changed. This makes it useful in circumstances where you want to avoid data modification by accident.
  • Hashability: "Frozenset" objects can be used as keys in dictionaries and as components in other sets because they are hashable.
  • Performance: "Frozenset" objects are performance optimized, particularly when working with large data sets. This is because a hash table, which enables quick lookups and insertions, is used to implement them.

Disadvantages of frozenset in Python

  • Immutability: Although it sometimes works to your advantage, immutability can also work against you. "frozenset" might not be the best choice if you frequently need to modify the set.
  • Lack of support for the "add," "remove," or "discard" methods limits the functionality of "Frozenset," which may limit its applicability in some circumstances.
  • Memory usage: Because "Frozenset" objects need extra overhead to ensure immutability and hashability, they can use more memory than regular sets. This might be a problem when memory usage is a crucial consideration.

Python Online Test


« Previous Tutorial Next Tutorial »



Liked this post? Share it!