Python: frozenset() function

frozenset() overview

The frozenset() function in Python initializes a frozen set from the given iterable. While a set is mutable, a frozenset is immutable (frozen). That means that once the frozenset is created, its elements remain and can't be changed. If we try to use the add function, an AttributeError exception is raised to inform us that the frozenset has no attribute add.

creating an empty frozenset

To create an empty frozenset, use the frozenset() function without passing any arguments. # create empty frozenset myEmptyFrozenSet = frozenset() print(myEmptyFrozenSet) The empty frozenset is created. The type of the returned object, can be verified by using the type() function. frozenset()

frozenset() of a tuple

The frozenset() function can create a frozenset of a tuple. # frozenset() of a tuple myTuple = (1, 2, 3, 4, 5) myFrozenSet = frozenset(myTuple) print(myFrozenSet) The frozenset is created. frozenset({1, 2, 3, 4, 5})

frozenset() of a dictionary

If a frozenset is created of a dictionary, only the keys are used. # frozenset of a dictionary myDict = {"first": 1, "second": 2, "third": 3} myFrozenSet = frozenset(myDict) print(myFrozenSet) The frozenset is created with the keys of the dictionary. The values are not used. frozenset({'second', 'third', 'first'})

frozenset() methods

To check the available methods of a frozenset, use the dir() function. # frozenset check available methods dir(myFrozenSet) All available methods are shown. The add() method is not available, since the frozenset is immutable. ['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union'] The table below shows the available methods of a frozenset:

frozenset() syntax

The syntax of the frozenset() function is: frozenset([iterable])

frozenset() arguments

The frozenset() function requires no arguments. If an iterable is given, its values are used to initialize the frozenset. If no iterable is given, an empty frozenset is created.

frozenset() return values

The frozenset() function returns the frozenset object.



Click to jump to section