Python built-in Method - frozenset()
The frozenset()
method in Python returns an immutable frozenset
object which is similar to a set, but is immutable, meaning that its contents cannot be changed once it is created.
The syntax for frozenset()
is as follows:
frozen_set = frozenset(iterable)
Here, iterable
is any iterable object like a list, tuple, set, or string. The frozenset()
method takes an iterable as an argument and returns a frozenset
object containing the unique elements from the iterable.
For example:
>>> s = set([1, 2, 3]) >>> fs = frozenset(s) >>> print(fs) frozenset({1, 2, 3})
In the example above, we create a set s
containing the elements 1, 2, and 3. We then pass s
as an argument to the frozenset()
method to create an immutable frozenset
object fs
. The print()
function is used to display the contents of fs
.
Since a frozenset
is immutable, it can be used as a key in a dictionary or as an element in another set, whereas a regular set cannot.
Note that since frozenset
objects are immutable, methods that modify a set such as add()
, remove()
, or clear()
are not available for frozenset
.