Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add set to set and make nested sets

Tags:

python

set

nested

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?

like image 272
John Avatar asked Jan 17 '15 20:01

John


1 Answers

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})}
like image 194
Ffisegydd Avatar answered Sep 28 '22 09:09

Ffisegydd