xrange() question

George Trojan george.trojan at noaa.gov
Tue Aug 5 21:50:05 CEST 2003


Bob Gailer wrote:

> 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?
>
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625
>
>------------------------------------------------------------------------
>
>
>---
>Outgoing mail is certified Virus Free.
>Checked by AVG anti-virus system (http://www.grisoft.com).
>Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
>  
>
It does. The reason I asked the question is that in the original example 
zip() needs only 4 elements from xrange(), so I was puzzled why the 
overflow was reached. But the following:

 >>> xrange(0, 3, 2)
xrange(0, 4, 2)

explains it (I think). Thanks to all for the answers.

George





More information about the Python-list mailing list