int vs long

Peter Otten __peter__ at web.de
Mon Jun 4 09:41:23 CEST 2007


Marc 'BlackJack' Rintsch wrote:

> In <1hz4uas.7jeyyu192pb8tN%aleax at mac.com>, Alex Martelli wrote:
> 
>> Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
>> 
>>> Dan Bishop <danb_83 at yahoo.com> writes:
>>> > If you ever do, it's trivial to write your own enumerate():
>>> > def enumerate(seq):
>>> >     index = 0
>>> >     for item in seq:
>>> >         yield (index, item)
>>> >         index += 1
>>> 
>>> That's a heck of a lot slower than the builtin, and if you're running it
>>> often enough for sys.maxint to be an issue, you may care about the
>>> speed.
>> 
>> Perhaps itertools.izip(itertools.count(), seq) might be faster (haven't
>> timed it, but itertools tends to be quite fast).

This approach is indeed much faster than the hand-crafted generator (10 vs
240% slowdown on my machine compared to the builtin)

> I think correct is more important than fast.  `itertools.count()` has the
> same issues that `enumerate()`:
> 
>>>> from itertools import count
>>>> from sys import maxint
>>>> c = count(maxint)
>>>> c.next()
> 2147483647
>>>> c.next()
> -2147483648
> 
> What I find most disturbing here, is that it happens silently.  I would
> have expected an exception instead of the surprise.

This is fixed in Python2.5:

>>> from itertools import count
>>> import sys
>>> c = count(sys.maxint)
>>> c.next(), c.next()
(2147483647, 2147483648L)

Peter



More information about the Python-list mailing list