How To Create A Set Of Sets In Python? (original) (raw)
Last Updated : 12 Feb, 2024
Sets are flexible data structures in Python that hold distinct items. There are situations in which you may need to construct a set of sets, even though sets are unordered and flexible in and of themselves. In this article, we will see how to create a set of sets.
**Note: We can't create a set of sets in Python as sets are mutable and not hashable preventing nesting within sets.
Create a Set of Sets in Python
Below are some of the ways by which we can Create a Set of Set In Python.
- Using Frozensets
- Using Set Comprehension
Create a Set of Sets Using Frozensets
The below approach code creates a set named **`set_of_sets` containing three frozensets: **`set1`, **`set2`, and **`set3`. Each frozenset is created directly using the **`frozenset()` constructor. These frozensets are then added to the set **`set_of_sets`, ensuring uniqueness. The **`print(set_of_sets)` displays the frozensets it contains.
Python3 `
using frozenset
set1 = frozenset({1, 2, 3}) set2 = frozenset({4, 5, 6}) set3 = frozenset({7, 8, 9})
set_of_sets = {set1, set2, set3}
#printing output print(type(set_of_sets)) print(set_of_sets)
`
Output
<class 'set'> {frozenset({1, 2, 3}), frozenset({4, 5, 6}), frozenset({8, 9, 7})}
Create a Set of Sets Using Set Comprehension
The below approach uses set comprehension to generate a set of sets, where each inner set is a frozenset containing a range of consecutive integers in increments of 3. The resulting **set_of_sets is displayed along with its type.
Python3 `
using set comprehension
set_of_sets = {frozenset(range(i, i+3)) for i in range(1, 10, 3)}
#printing result print(type(set_of_sets)) print(set_of_sets)
`
Output
<class 'set'> {frozenset({1, 2, 3}), frozenset({4, 5, 6}), frozenset({8, 9, 7})}
Conclusion:
In conclusion, constructing a set of sets in Python can be achieved through various methods, such as using a list of sets, frozensets, or set comprehension, each offering distinct advantages based on the specific requirements of your application. These approaches showcase the flexibility of sets in accommodating diverse data structures. Overall, the choice of method depends on the desired characteristics and functionality for the set of sets in your Python program.