We know in Python, a set can be defined by writing out all its elements like this:
a_set={1,"xyz"}
And books of Python all say elements of a set can be any datatype. So we should be able to write out a set containing a set. I tried to write it as:
a_set={1,{"xyz"}}
But IDLE reported an error:
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
a_set={1,{"xyz"}}
TypeError: unhashable type: 'set'
I think this may be because Python is trying to understand it as a dictionary. Then, how to write out a set containing a set in Python?
So far, most of our sets have contained atomic elements (such as numbers or strings) or tuples (e.g. pairs of numbers). Sets can also contain other sets. For example, {Z, Q} is a set containing two infinite sets.
The set add() method adds a given element to a set if the element is not present in the set. Syntax: set. add(elem) The add() method doesn't add an element to the set if it's already present in it otherwise it will get added to the set.
The inner most sets need to be of type frozenset which is an immutable version of a set.
>>> a_set = {1, frozenset(['xyz'])}
>>> a_set
set([1, frozenset(['xyz'])])
From the docs:
class frozenset([iterable])
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With