xrange() question

Peter Abel p-abel at t-online.de
Tue Aug 5 15:27:26 EDT 2003


George Trojan <george.trojan at noaa.gov> wrote in message news:<bgogn2$vmk$1 at news.nems.noaa.gov>...
> 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
> ...
> 0 0
> 1 1
> 2 2
> 3 3
> 4 4
> 5 5
> 6 6
> 7 7
> 
> George

I think the problem is that sys.maxint is ?? I guess odd if 
remember my english lesson well ??
>>> print sys.maxint
2147483647
And if you icrement by 2 you will reach sys.maxint+1 to be
tested if the end of xrange(start,end,step) is reached - 
what is ** an Overflow** .
So the solution will be:
>>> for n, x in zip(range(4), xrange(0, sys.maxint-1, 2)):
... 	print n, x
... 
0 0
1 2
2 4
3 6

Hope this helps.
Regards
Peter




More information about the Python-list mailing list