range() is not the best way to check range?

Summercoolness at gmail.com Summercoolness at gmail.com
Mon Jul 17 22:41:11 EDT 2006


it seems that range() can be really slow:

the following program will run, and the last line shows how long it ran
for:

import time

startTime = time.time()

a = 1.0
for i in range(0, 30000):
    if i in range (0, 10000):
        a += 1
    if not i % 1000: print i

print a, "   ", round(time.time() - startTime, 1), "seconds"


---------------------------------
the last line of output is
---------------------------------

10001.0     22.8 seconds

so if i change the line

    if i in range (0, 10000):

to

    if i >= 0 and i < 10000:

the the last line is

10001.0     0.2 seconds

so approximately, the program ran 100 times faster!

or is there an alternative use of range() or something similar that can
be as fast?




More information about the Python-list mailing list