What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Frozen Sets in Python: frozenset() function with Examples

  • Jan 31, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
Frozen Sets in Python: frozenset() function with Examples

Today we are going to understands about Frozen Sets in Python, how to create them, and how it is different from normal sets. Let's learn it with some examples and code.

What is a Frozenset in Python?

Sets are a type of sequential data that are unordered, and unindexed meaning accessing an element in a set through indexing is impossible. Sets are modifiable meaning they can be modified after the creation of the set at any time. A variation of sets that provides a version of sets with immutability is Frozen Sets. 

In Python, Frozen Sets are created through the method frozensets() which takes iterable data and converts them into a frozen set. The term “Iterable Data” means sequential data that can be iterated upon. Iterable data types in python include Lists and Tuples that are usually in the format [1,2,3] and (1,2,3) respectively.

The primary difference between lists and tuples is that lists are mutable and tuples are immutable. Lists have methods such as append() with which we can add more list elements and we can use indexing to change the values of lists but both those operations are not possible in tuples.

Frozenset is a data type in python that is immutable and unordered. It is used when an unchangeable set is required, such as an element of another set or as a key in a dictionary.

Also, learn how to convert a set to a list in Python.

Let us explore the function more in-depth. frozensets() is a built-in python function used to create Frozen Sets. Different iterable data can be passed to frozensets() function to create frozensets. Let us explore some such examples:

Creating a frozen set from a list

example_list = [1,2,3,4,5]
frozen_set = frozenset(example_list)

print(example_list)
print(type(example_list)

print(frozen_set)
print(type(frozen_set))

 

Output:

[1,2,3,4,5]
<class 'list'>
frozenset({1,2,3,4,5})
<class 'frozenset'>

 

In the above example, we have created a list with elements 1,2,3,4, and 5 and then we called the frozenset() function with the list as the parameter and assigned it to the frozen_set variable. We then printed the list and the type of the list which outputted the list and the class of the list being ‘list’.

We then printed the frozen_set which outputted the value frozenset({1,2,3,4,5}). The reason behind why the word frozenset is in the output is so that it can be easily distinguishable from a normal set which would look like {1,2,3,4,5}.

In the next line, we print the type of the frozen_set variable and it outputs the class ‘frozenset’ verifying the datatype once again.

Creating a frozen set from a tuple

The code for creating a frozen set from a tuple is essentially the same as the list example with the one difference being that there is a tuple instead of a list. Here’s the code:

example_tuple = (1,2,3,4,5)
frozen_set = frozenset(example_tuple)

print(example_tuple)
print(type(example_tuple)

print(frozen_set)
print(type(frozen_set))

 

Output:

(1,2,3,4,5)
<class 'tuple'>
frozenset({1,2,3,4,5})
<class 'frozenset'>

 

The output is identical to the example before with the exception that it's a tuple instead of a list.

As mentioned above, frozensets() function takes iterable data such as lists and tuples and we have explored both in the above two examples. But, lists and tuples are not the only datatypes that the function frozensets() accepts.

We can create a frozen set from a dictionary too but it works very differently when compared to lists and/or tuples. 

frozensets() function and dictionaries

Dictionary data type in python is used to store values in pairs of keys and values. Every element in a dictionary is a key-value pair formatted with a ‘:’ between a key and a value.

So, in theory, due to the added dimension of every key containing a value in a dictionary, it seems impossible to convert a dictionary into a frozen set because sets do not accept key-value pairs but, on the contrary, we can indeed create a frozen set from a dictionary.

The frozensets() function when passed with a dictionary will create a frozen set of all the keys of the dictionary. Here is the demonstration through code:

example_dictionary = {"key1":"value1", "key2":"value2", "key3":"value3"}
frozen_set = frozenset(example_dictionary)

print(example_dictionary)
print(type(example_dictionary))

print(frozen_set)
print(type(frozen_set))

 

Output:

{"key1":"value1", "key2":"value2", "key3":"value3"}
<class 'dict'>
frozenset({'key1', 'key2', key3'})
<class 'frozenset'>

 

Here, we created a dictionary and then created a frozen set from the dictionary and as you can see, the frozen set contains all the key values of the dictionary.

So we explored different ways a frozen set can be created and let us now explore the immutability and the lack of indexability aspects of the frozen set datatype. 

 

Exploring the frozen set data type

Let's look at the below example:

x = frozenset([1,2,3])
print(x[2])

 

Output:

TypeError                                 Traceback (most recent call last)
      x = frozenset([1,2,3])
- - ->print(x[2])
TypeError: 'frozenset' object does not support item assignment

 

In the above code, we tried to access an element from the frozen set and that led to an error. The error is TypeError because the type ‘frozenset’ does not support indexing.

A similar error will be the result if you try changing a value from a frozen set. Here’s an example:

x = frozenset([1,2,3])
x[2] = 7
print(x)

 

Output:

TypeError                                 Traceback (most recent call last)
      x = frozenset([1,2,3])
- - ->x[2] = 7
      print(x)
TypeError: 'frozenset' object does not support item assignment

 

So, through these examples, we can understand that it is impossible to index or modify a frozen set. Let us now understand the reason why frozen sets are so prominently used. 

One more thing to note: We cannot perform add, update or remove operations on frozensets because they are immutable. We can only do normal set operations like copy, difference, union, intersection, or symmetric_difference.

Frozen Sets vs Sets

The data type Set is built upon frozen sets with the addition of mutating methods. Memory-wise, a frozen set should be more efficient when compared to a set due to the lack of mutation methods in the class.

Although there is no significant difference in performance, frozen sets should be preferred when there is no need for any mutations in the data necessary. A frozen set is hashable. That means each value in a frozen set contains a hash value, an integer used to identify an element that never changes in the lifetime of the frozen set.

Due to the immutable nature of frozen sets, an advanced use case of frozen sets is hashability.

Conclusion

In conclusion, Frozen Sets are highly useful datatypes with useful properties that every python programmer can make use of. Through this article, we have successfully built foundational knowledge of intricate data types such as sets and frozen sets that we can apply in programming in DSA, projects, etc.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.