user1609515
user1609515

Reputation: 19

set consisting of an empty set

To get an empty set in python I use {} and it works.

I need to use the empty set as an element in a set.

But {{}} yields an error and {set()} too.

Is there a way?

Upvotes: 1

Views: 280

Answers (2)

The contents of sets (and the keys of dictionaries) can only be immutable values. That means that their contents can't change. If you're using a regular set, its contents can be changed with, for example, the .add and .remove methods, so it's not possible to put it inside another set.

Instead, you need to use a frozenset. It behaves the same as a set except that you can't change its contents after it is created.

print frozenset([ frozenset() ]) == frozenset([ frozenset() ]) # True

Upvotes: 7

AI Generated Response
AI Generated Response

Reputation: 8845

{} makes an empty dict. You cannot have keyless items inside of dicts. You cannot create sets inside of sets because they are unhashable.

Upvotes: 1

Related Questions