Hashable

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jan 26 12:46:49 CET 2008


On Sat, 26 Jan 2008 11:10:03 +0000, Simon Pickles wrote:

> Hi,
> 
> The term 'hashable'.
> 
> Am I right in thinking it means it can be indexed? like a string or a
> dict?


No.


A hash function is a function which takes an arbitrary object and 
generates an integer from it.

Python has a built-in hash function hash(). It says:

help(hash):

hash(...)
    hash(object) -> integer

    Return a hash value for the object.  Two objects with the same 
    value have the same hash value.  The reverse is not necessarily 
    true, but likely.


Examples:

>>> hash(5.5)
1476493312
>>> hash('five')
202874452
>>> hash('fivf')
202874455
>>> hash(None)
54045056


Not all objects are hashable:

>>> hash([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable


Python dictionaries are "hash tables". A hash table is a data structure 
that let's you look up a key in (virtually) a constant amount of time no 
matter how many items there are in the table. It does this by calculating 
the hash of the key, then using that hash to calculate the index in the 
table where it expects to find the key's data. A good hash table (like 
Python dicts) is *very* fast.

But notice that the object which _uses_ the hash (the dict) is not 
hashable itself; and that the objects which are hashable (strings, ints, 
floats, etc.) don't necessarily have an index. Strings do, tuples do, but 
ints and floats and other objects don't.



-- 
Steven



More information about the Python-list mailing list