enumerate overflow

Tim Chase python.list at tim.thechases.com
Wed Oct 3 15:43:18 CEST 2007

>> in python2.4, i read lines from a file with
>> for lineNum, line in enumerate(f): ...
>> However, lineNum soon overflows and starts counting backwards. How do
>> i force enumerate to return long integer?
> Most probably you can't, because it is a C-written function I presume.
> But as python 2.4 has generators, it's ease to create an enumerate yourself:
> def lenumerate(f):
>      i = 0
>      for line in f:
>          yield i, line
>          i += 1

I'd consider this a bug:  either in the implementation of 
enumerate(), or in the documentation


which fails to mention such arbitrary limitations.  The 
documentation describes what you create as an lenumerate() function.

Most likely, if one doesn't want to change the implementation, 
one should update the documentation for enumerate() to include a 
caveat like xrange() has


Note: xrange() is intended to be simple and fast. Implementations 
may impose restrictions to achieve this. The C implementation of 
Python restricts all arguments to native C longs ("short" Python 
integers), and also requires that the number of elements fit in a 
native C long.

While yes, it's easy enough to create the above lenumerate 
generator (just as it's only slightly more work to create an 
lxrange function), it would be good if the docs let you know that 
you might need to create such a function


More information about the Python-list mailing list