Python Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. It can be done with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
If no parameters are passed, it returns an empty frozenset.
Python
# Python program to demonstrate differences # between normal and frozen set # Same as {"a", "b","c"} normal_set = set ([ "a" , "b" , "c" ]) print ( "Normal Set" ) print (normal_set) # A frozen set frozen_set = frozenset ([ "e" , "f" , "g" ]) print ( "\nFrozen Set" ) print (frozen_set) # Uncommenting below line would cause error as # we are trying to add element to a frozen set # frozen_set.add("h") |
Output:
Normal Set {'a', 'c', 'b'} Frozen Set {'e', 'g', 'f'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Sets in Python
A Set in Python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes as we do in lists.