Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Set of Sets in Python?

I'm trying to make a set of sets in Python. I can't figure out how to do it.

Starting with the empty set xx:

xx = set([]) # Now we have some other set, for example elements = set([2,3,4]) xx.add(elements) 

but I get

TypeError: unhashable type: 'list' 

or

TypeError: unhashable type: 'set' 

Is it possible to have a set of sets in Python?

I am dealing with a large collection of sets and I want to be able to not have to deal duplicate sets (a set B of sets A1, A2, ...., An would "cancel" two sets if Ai = Aj)

like image 800
Matt Avatar asked May 09 '11 00:05

Matt


People also ask

Can you create a set of sets in Python?

Creating a SetSets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a 'comma'. Note: A set cannot have mutable elements like a list or dictionary, as it is mutable.

How do I create a list set in Python?

The simplest way to convert list to set in Python is by using the set() function. The set() method is used to convert an iterable element such as a list, dictionary, or tuple into the set.

Can we create nested sets in Python?

They are immutable, so they cannot be changed and we can use them to create nested sets.


1 Answers

Python's complaining because the inner set objects are mutable and thus not hashable. The solution is to use frozenset for the inner sets, to indicate that you have no intention of modifying them.

like image 73
a3nm Avatar answered Sep 20 '22 03:09

a3nm