Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't Python sets hashable?

Tags:

python

hash

set

I stumbled across a blog post detailing how to implement a powerset function in Python. So I went about trying my own way of doing it, and discovered that Python apparently cannot have a set of sets, since set is not hashable. This is irksome, since the definition of a powerset is that it is a set of sets, and I wanted to implement it using actual set operations.

>>> set([ set() ]) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set' 

Is there a good reason Python sets are not hashable?

like image 364
Dan Burton Avatar asked Jun 10 '11 18:06

Dan Burton


People also ask

Are sets in Python hashable?

Python sets can only include hashable objects. 00:43 That means that they can include immutable objects because all immutable objects are hashable and they can include mutable objects that are hashable. So, some examples that you've probably seen of immutable objects are tuples, strings, integers, and Booleans.

Why are Python lists not hashable?

This error occurs when trying to hash a list, which is an unhashable object. For example, using a list as a key in a Python dictionary will cause this error since dictionaries only accept hashable data types as a key. The standard way to solve this issue is to cast a list to a tuple, which is a hashable data type.

Why are Python sets hashable?

So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set. An object is hashable if it has a hash value that does not change during its entire lifetime.

Why are mutable objects not hashable?

While none of the built-in mutable objects are hashable, it is possible to make a mutable object with a hash value that's not mutable. It's common for only a portion of the object to represent its identity, while the rest of the object contains properties that are free to change.


1 Answers

Generally, only immutable objects are hashable in Python. The immutable variant of set() -- frozenset() -- is hashable.

like image 162
Sven Marnach Avatar answered Sep 20 '22 15:09

Sven Marnach