xrange() question

Peter Abel p-abel at t-online.de
Wed Aug 6 15:01:02 CEST 2003


Bob Gailer <bgailer at alum.rpi.edu> wrote in message news:<mailman.1060095609.4903.python-list at python.org>...
> At 02:27 PM 8/5/2003 +0000, George Trojan wrote:
> 
> >Why do I get an overflow error here:
> >
> > > /usr/bin/python
> >Python 2.2.2 (#1, Feb 24 2003, 19:13:11)
> >[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2
> >Type "help", "copyright", "credits" or "license" for more information.
> > >>> import sys
> > >>> for n, x in zip(range(4), xrange(0, sys.maxint, 2)):
> >...     print n, x
> >...
> >Traceback (most recent call last):
> >  File "<stdin>", line 1, in ?
> >OverflowError: integer addition
> >
> >but not here:
> >
> > >>> for n, x in zip(range(8), xrange(0, sys.maxint)):
> >...     print n, x
> [snip]
> Consider:
> 
>  >>> for x in xrange(sys.maxint-2,sys.maxint,2):x
> ...
> 2147483645
> 
> for x in xrange(sys.maxint-1,sys.maxint,2):x
> ...
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> OverflowError: integer addition
> 
> Does this give you any clues?
> 
YES, it does.
At my opinion it's completely in accordance with my above said.
You start with sys.maxint - 1 = 2147483646 and then get this
as first element. Next - I guess - Python will check if 2147483646 + 2
is bigger or equal than the ending criteria, what is sys.maxint. But this
check will fail because 2147483646 + 2 causes an overflow.
So for me the global rule is:
If you have a  therm like **range(start,end,step)**,
it is higly recommmended, that "start" + "N" * "step" is equal to "end" for a
certain "N", where "N" is an integer. This is necessary when "end" is 
sys.maxint.

Regards
Peter


> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625
> 
> --




More information about the Python-list mailing list