It gives me error while creating {{2}, 3, 4} set element inside a set.
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
Is there any alternative way to do that? Thanks in advance.
It gives me error while creating {{2}, 3, 4} set element inside a set.
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
Is there any alternative way to do that? Thanks in advance.
Sets can only contain hashable objects. But sets themselves are not hashable. So a set can't contain another set.
(Aside from that, your code has a syntax error because {2}.3 is invalid syntax. But if you change it to {{2}, 3, 4} it still won't work, for the reason I mentioned above.)
In Python, in general, mutable types like set are not hashable. It's not just a coincidence that they can't be used as set elements or dict keys—that's actually the whole point:
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()method), and can be compared to other objects (it needs an__eq__()method). Hashable objects which compare equal must have the same hash value.Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their
id().
The frozenset type exists for pretty much this purpose:
There are currently two built-in set types,
setandfrozenset. Thesettype is mutable — the contents can be changed using methods likeadd()andremove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. Thefrozensettype is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.
Even though their items must all be immutable/hashable types, sets themselves are a mutable/nonhashable type. You can either add or remove items from a set using methods such as set.add, set.pop, or set.remove. Thus, you cannot put a set inside another set because the item might be changed at any time.
Instead, you can use a frozenset, which is an immutable/hashable set:
>>> {frozenset({2}), 3,4}
set([frozenset([2]), 3, 4])
>>>
Keep in mind however that this only works because frozensets cannot be changed after they are created (there is no way to add or remove items).