xrange() question

Michael Hudson mwh at python.net
Tue Aug 5 10:44:36 EDT 2003


George Trojan <george.trojan at noaa.gov> writes:

> 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

The first thing to note is that it's not as subtle as you paint:

>>> xrange(0, sys.maxint)
xrange(2147483647)
>>> xrange(0, sys.maxint, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OverflowError: integer addition

as to why, I imagine the latter computes something-or-other in a
suboptimal way and overflows.  You could try reading the source if you
really care.

Cheers,
mwh

-- 
  Never meddle in the affairs of NT. It is slow to boot and quick to
  crash.                                             -- Stephen Harris
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html




More information about the Python-list mailing list