How to Create a Set of Sets in Python

Vaibhav Vaibhav Feb 02, 2024
How to Create a Set of Sets in Python

As a programmer, one should have a piece of good knowledge of data structures. There are many data structures in computer science, out of which arrays and sets are very easy to understand. Since this article is not about data structures, we will not dive deep into them, rather talk specifically about Sets.

In Python, we can create an array of arrays or a list of lists. However, this is not true for sets. We cannot create a set of sets in Python. Do you not believe that? Try the following code.

print({{1, 2}, {2, 3}})

The code above will throw an error, which is as follows.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unhashable type: 'set'

Since sets are mutable, they can’t be hashed. Since a set needs hashable values to maintain uniqueness and reject duplicate values, we can’t create a set of sets this way. Instead, we have to follow some different approaches.

Mutable means that the content of the data structure can be altered, while immutable means that the content of the data structure can’t be altered. Some examples of mutable data structures are lists, sets, and dictionaries. And, some examples of immutable data structures are strings, frozenset, and tuples.

Hashable means that the data structure can be represented as a unique string inside the memory, while unhashable means that the data structure cannot be represented as a unique string inside the memory.

Create Set of Sets Using frozenset in Python

frozenset is a type of set pre-built in Python. A frozenset and a set perform the same function: store unique values and reject duplicate values added to them. However, a frozenset is immutable and hashable, while a set is mutable and unhashable. Since a frozenset is immutable, it can be used as a key inside a dictionary and stored inside a set, because a set can only store immutable values. Let’s understand this better with some Python code.

a = set([frozenset([1, 2]), frozenset([2, 3]), frozenset([3, 4])])
print(a)

The output of the code above is as follows.

{frozenset({3, 4}), frozenset({2, 3}), frozenset({1, 2})}

To learn more about frozenset, refer to the official Python documentation here.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Set