What is a frozenset?
frozenset()
is a function in Python that makes an iterable object immutable. In other words, frozenset()
freezes the iterable objects and makes them unchangeable.
What does iterable mean in Python?
Iterable
in Python means an object capable of returning its members one at a time, allowing it to be iterated over in a loop. Python has 4 built-in iterable data types: list
, dict
, tuple
, and set
.
Example of using frozenset() for a tuple
The following is an example of using frozenset()
for a tuple. We first define a tuple and check its data type.
# define a tuple
tuple_0=(1,2,3)
# print it out
print(tuple_0)
# check data type
print(type(tuple_0))
(1, 2, 3) <class 'tuple'>
Then, we define a frozenset based on the tuple defined earlier. We can see it becomes a frozenset type.
# define a frozenset from the tuple defined earlier
frozenset_0=frozenset(tuple_0)
# print the frozenset out
print(frozenset_0)
#check datatype
print(type(frozenset_0))
frozenset({1, 2, 3}) <class 'frozenset'>
Unlike tuple, frozenset is not subscriptable
Frozenset
is not subscriptable. The following code shows that you can print the first element for a tuple
, but not in a frozenset
.
# generate a tuple
tuple_0=(1,2,3)
# check data type
print(type(tuple_0))
# print out the first element of the tuple
print(tuple_0[0])
<class 'tuple'> 1
# generate a frozenset from the tuple defined earlier
fset=frozenset(tuple_0)
# check data type
print(type(fset))
# trying to print out the first element of the frozenset
print(fset[0])
<class 'frozenset'> TypeError: 'frozenset' object is not subscriptable
Example of using frozenset() for a dictionary
For a dictionary, frozenset()
only takes keys to create a frozenset.
dic_0={"brand":"Tesla","year":2021}
fset_1=frozenset(dic_0)
print(fset_1)
frozenset({'brand', 'year'})