[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Simon Pickles

1/26/2008 11:10:00 AM

Hi,

The term 'hashable'.

Am I right in thinking it means it can be indexed? like a string or a dict?

Thanks

Si

--
Linux user #458601 - http://coun....



1 Answer

Steven D'Aprano

1/26/2008 11:47:00 AM

0

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