John
John

Reputation: 429

Add set to set and make nested sets

In Python I want to make sets consisting of sets, so I get a set of sets (nested sets).

Example:

{{1,2}, {2,3}, {4,5}}

However when I try the following:

s = set()
s.add(set((1,2)))

I get an error:

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    s.add(set((1,2)))
TypeError: unhashable type: 'set'

Can anyone tell me where my mistake is and how I achieve my goal please?

Upvotes: 7

Views: 14017

Answers (2)

user2555451
user2555451

Reputation:

You cannot have a set of sets because sets are unhashable objects; they can be mutated by adding or removing items from them.

You will need to use a set of frozensets instead:

s = set()
s.add(frozenset((1,2)))

Demo:

>>> s = set()
>>> s.add(frozenset((1,2)))
>>> s.add(frozenset((2,3)))
>>> s.add(frozenset((4,5)))
>>> s
{frozenset({1, 2}), frozenset({2, 3}), frozenset({4, 5})}
>>>

Frozensets are like normal sets in every respect except that they cannot be mutated. This feature makes them hashable and allows you to use them as items of a set or keys of a dictionary.

Upvotes: 3

Ffisegydd
Ffisegydd

Reputation: 53688

Your issue is that sets can only contain hashable objects, and a set is not hashable.

You should use the frozenset type, which is hashable, for the elements of the outer set.

In [3]: s = set([frozenset([1,2]), frozenset([3,4])])

In [4]: s
Out[4]: {frozenset({1, 2}), frozenset({3, 4})}

Upvotes: 9

Related Questions