Python Set in Set - A set can't have a set

A Python set can't have sets.

a = {1, 2, {3, 4}}
# TypeError: unhashable type: 'set'

What does the error message mean? A set can have only hashable elements and set is not hashable. The hashable object is an object whose hash value is not None and doesn't change in its lifetime.

If you want to insert it, the child set should be converted to the immutable set, that is frozenset.

a = {1, 2, frozenset({3, 4})}


Powered by Markdown