The set collection is a mutable sequence, and the program can change the elements in the sequence; the frozenset collection is an immutable sequence, and the program cannot change the elements in the sequence. All methods in the set collection that can change the collection itself, such as remove, discard, add, etc., are not supported by frozenset; methods in the set collection that do not change the collection itself are supported by frozenset.
We can enter dir (frozenset) in the interactive programming environment to see the methods supported by the frozenset collection:
dir (frozenset)
These methods of the frozenset collection have the same function as the methods of the same name in the set collection.
Fronzenset can be used in two cases:
The following program demonstrates the use of frozenset:
s = {'Jason', 'Nicole', 'Mark'} fs = frozenset (['Iven', 'Harry']) s_sub = {'Peter', 'Ball'} #Add frozenset to the set collection s.add (fs) print ('s =', s) #Add child set collection to set collection s.add (s_sub) print ('s =', s)
The output is:
s = {'Mark', 'Jason', 'Nicole', frozenset({'Iven', 'Harry'})}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
[ipython-input-161-57ee5adf8664] in [module]
1 #Add child set collection to set collection
----> 2 s.add (s_sub)
3 print ('s =', s)
TypeError: unhashable type: 'set'
It should be noted that the elements of the set itself must be immutable, so the elements of the set cannot be set, only frozenset. Line 4 adds frozenset to the set, which is fine, because frozenset is immutable; however, line 8 attempts to add a subset to the set, which is not allowed because set is mutable.
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises