[Tutor] Workaround for limitation in xrange()?

Kent Johnson kent37 at tds.net
Tue Oct 10 17:34:34 CEST 2006


Dick Moores wrote:
>  >>> for x in xrange(2**31):
>      pass
> 
> Traceback (most recent call last):
>    File "<pyshell#16>", line 1, in <module>
>      for x in xrange(2**31):
> OverflowError: long int too large to convert to int
>  >>>
> 
> I can think of 2 workarounds for this 2**31 limitation in xrange(). 
> Use a while loop instead. Or use 2 or more for loops, keeping the 
> number of cycles in each under 2**31.
> 
> Are there others?

Encapsulate the while loop in a generator:
def count(limit):
   n=0
   while n<limit:
     yield n
     n += 1

Kent



More information about the Tutor mailing list