4.6. Frozensets¶
Sets are mutable, and may therefore not be used, for example, as keys in dictionaries.
Another problem is that sets themselves may only contain immutable (hashable) values, and thus may not contain other sets.
Because sets of sets often occur in practice, there is the frozenset type, which represents immutable (and, therefore, hashable) sets.
4.6.1. Quick Example¶
>>> a = frozenset([1, 2, 3])
>>> b = frozenset([2, 3, 4])
>>> a.union(b)
frozenset([1, 2, 3, 4])
4.6.2. Set of Sets¶
Sets may only contain immutable (hashable) values, and thus may not contain other sets, in which case frozensets can be useful. Consider the following example:
>>> a = set([1, 2, 3])
>>> b = set([2, 3, 4])
>>> a.add(b)
>>> a.add(frozenset(b))
4.6.3. Using set as key in a dictionary¶
If you want to use a set as a key dictionary, you will need frozenset:
>>> fa = {frozenset([1,2]): 1}
>>> fa[ frozenset([1,2]) ]
1
4.6.4. Methods¶
frozensets have less methods than sets.
There are some operators similar to sets (intersection(), union(), symmetric_difference(), difference(), issubset(), isdisjoint(), issuperset()) and a copy() method.