[Tutor] for loop for long numbers
Martin A. Brown
martin at linux-ip.net
Mon Aug 3 23:20:00 CEST 2015
Greetings Dima,
> 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.
> Can some on help me?
Ah, range and xrange. It would help us to know which Python version you are
using, as there is a very slight difference in how Python 2.x and Python 3.x
deal with range().
Well, if you are using Python 2.x, I'm assuming that you are seeing something
like this, when you use range():
>>> range(0,9000000000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
That's because range() is trying to return you a list, and is
allocating a bunch of memory so that it can create the list. You
probably don't have this much memory in your machine.
I didn't have any problem using xrange() in a for loop in Python
2.7.3. None at all.
I also gave Python 3.3.0 a try, by running this:
for i in range(0, 9000000000):
x = 0
This also ran without a hitch....
So, perhaps you are having some sort of other problem. Would you
like to provide more detail?
-Martin
P.S. I wrote a little function to see if I could figure out how long
it would take to run a for loop on your 9 billion (~9e9), without
actually running it. I started by timing the loop on range(0,
100,000) and then increased it until it took an appreciable amount
of time for a human. At 1e9 (range of 1 billion), it took my little
anemic laptop about 12.8 seconds to count through the loop. So,
before accounting for any work that you plan to undertake inside the
loop, you have a runtime of ~115 seconds.
--
Martin A. Brown
http://linux-ip.net/
More information about the Tutor
mailing list