xrange not hashable - why not?

Hans Nowak hans at zephyrfalcon.org
Sun Jan 25 19:06:31 EST 2004


Gerrit Holl wrote:
> Hi,
> 
> why is an xrange object not hashable?
> I was trying to do something like:
> 
> comments = {
>     xrange(0, 4): "Few",
>     xrange(4, 10): "Several",
>     xrange(10, 100): "A lot",
>     xrange(100, sys.maxint): "Can't count them"}
> for (k, v) in comments.items():
>     if n in k:
>         commentaar = v
>         break

So far, everybody who replied seems to agree or assumes that xrange indeed 
isn't hashable.  However:

Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import sys
 >>> comments = {
...     xrange(0, 4): "Few",
...     xrange(4, 10): "Several",
...     xrange(10, 100): "A lot",
...     xrange(100, sys.maxint): "Can't count them"}
 >>> comments
{xrange(4): 'Few', xrange(4, 10): 'Several', xrange(100, 2147483647): "Can't 
count them", xrange(10, 100): 'A lot'}

Sure enough, that dict works.  Let's try something else then:

 >>> a = xrange(10)
 >>> b = xrange(20)
 >>> hash(a), hash(b)
(7774576, 7775104)

It seems that xrange objects do have a hash value.  The other part of the code 
works as well:

 >>> n = 3
 >>> for k, v in comments.items():
...     if n in k:
...         commentaar = v
...         break
...
 >>> commentaar
'Few'

I don't really see what the problem is...?

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/






More information about the Python-list mailing list