[Tutor] for loop for long numbers

Steven D'Aprano steve at pearwood.info
Tue Aug 4 03:50:20 CEST 2015


On Mon, Aug 03, 2015 at 09:15:45PM +0300, Dima Kulik wrote:
>  Hi to all.
> Can you help me plz.
> I want to make a for loop with a huge numbers.
> for example:
> 
> for i in range (0,9000000000):
>  make_some_code
> 
> but range and xrange cant operate with such big numbers. 


In Python 2, range() builds the entire list up front, so 
range(9000000000) will require *at least* 144000032000 bytes, or 134 GB 
of memory just for the list. That's 134 GIGABYTES.

So forget about using range.

In Python 2, xrange() is limited in the largest number you can use. If 
your Python is compiled for a 32-bit operating system:

py> xrange(2**31-1)
xrange(2147483647)
py> xrange(2**31)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long


2**31 is much smaller than the number you use:

py> 9000000000 - 2**31
6852516352L


If you have a 64-bit operating system, you can use a 64-bit version of 
Python, and the limit will be something like 2**63 - 1 or so. I can't 
test this myself, as I have a 32-bit system like you.

Another alternative is to use itertools.count:

from itertools import count
for i in count(0):
    if i >= 9000000000: break


Or you can upgrade to Python 3, where range() has no restrictions until 
you run out of memory, and can work with ludicrously big numbers:

py> range(10**50)
range(0, 100000000000000000000000000000000000000000000000000)



-- 
Steve


More information about the Tutor mailing list