xrange not hashable - why not?

Andrew MacIntyre andymac at bullseye.apana.org.au
Sun Jan 25 19:17:21 EST 2004


On Sun, 25 Jan 2004, Gerrit Holl wrote:

> why is an xrange object not hashable?

xrange() returns an iterator.  iterators seem universally unhashable,
probably because they can't be deemed "concrete", though I can't find
anything in the 2.3.3 docs about this - perhaps the relevant PEPs might.

> 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

Even if it worked, there's a nasty performance trap in the sys.maxint
case: if the sys.maxint case is the first returned by the items() method
call and n < 100, the "in" will evaluate the sys.maxint xrange iterator.

Without more info, I don't see why a dictionary is that useful in this
case, so I would actually write the above as:

comments = (((0, 4), "Few"),
            ((4, 10), "Several"),
            ((10, 100), "A lot"))
commentaar= "Can't count them"
for (k, v) in comments:
     if n in xrange(*k):
         commentaar = v
         break

--
Andrew I MacIntyre                     "These thoughts are mine alone..."
E-mail: andymac at bullseye.apana.org.au  (pref) | Snail: PO Box 370
        andymac at pcug.org.au             (alt) |        Belconnen  ACT  2616
Web:    http://www.andymac.org/               |        Australia




More information about the Python-list mailing list