w3resource

Frozenset immutability demonstration: Python code example

Python Frozenset Views Data Type: Exercise-8 with Solution

Write a Python program that demonstrates the immutability of a frozenset by attempting to add or remove elements from it.

Sample Solution:

Code:

def main():
    original_frozenset = frozenset([1, 2, 3, 4, 5, 6])

    # Attempt to add an element to the frozenset
    try:
        modified_frozenset = original_frozenset.add(7)
    except AttributeError:
        print("It is not possible to add an element to a frozenset!")

    # Attempt to remove an element from the frozenset
    try:
        modified_frozenset = original_frozenset.remove(2)
    except AttributeError:
        print("It is not possible to remove an element from a frozenset!")

if __name__ == "__main__":
    main()

Output:

It is not possible to add an element to a frozenset!
It is not possible to remove an element from a frozenset!

In the exercise above, we are trying to use the "add()" and "remove()" methods to modify the original_frozenset. However, both of these operations will raise an "AttributeError" because a 'frozenset' does not have these methods due to its immutability.

Flowchart:

Flowchart: Frozenset immutability demonstration: Python code example.

Previous: Check disjoint frozensets: Python code and example.
Next: Hashable composite keys using frozenset: Python code example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-index-frozenset-views-exercise-8.php