Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to write a set containing a set?

Tags:

python

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?

like image 447
user2384994 Avatar asked May 17 '13 23:05

user2384994


People also ask

Can set contain sets?

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.

How do you add a set to a set in Python?

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.


1 Answers

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.

like image 60
Jon Clements Avatar answered Nov 13 '22 15:11

Jon Clements