To create a Set of Sets in Python, you can use sets to represent sets. You create individual sets as sets and then add them to another set.
In this example,
set1
, set2
, and set3
. We add the elements 1, 2, 3
to set1
, 4, 5, 6
to set2
, and 7, 8, 9
to set3
.setOfSets
and add set1
, set2
, and set3
to it. This nests the three sets within a single set.setOfSets
using a for loop. Within the loop, we print each individual set to the standard output.set1 = {1, 2, 3}
set2 = {4, 5, 6}
set3 = {7, 8, 9}
setOfSets = {set1, set2, set3}
for set_ in setOfSets:
print(set_)
Output: {1, 2, 3} {4, 5, 6} {8, 9, 7}
In this example,
setA
, setB
, and setC
. We add the elements "apple", "banana", "cherry"
to setA
, "dog", "elephant", "fox"
to setB
, and "grape", "honeydew", "kiwi"
to setC
.setOfStringSets
and add setA
, setB
, and setC
to it. This nests the three sets within a single set.setOfStringSets
using a for loop. Within the loop, we print each individual set to the standard output.setA = {'apple', 'banana', 'cherry'}
setB = {'dog', 'elephant', 'fox'}
setC = {'grape', 'honeydew', 'kiwi'}
setOfStringSets = {setA, setB, setC}
for set_ in setOfStringSets:
print(set_)
Output: {'banana', 'cherry', 'apple'} {'fox', 'elephant', 'dog'} {'kiwi', 'grape', 'honeydew'}
In this tutorial, we learned How to create a Set of Sets in Python language with well detailed examples.