Why I think range is a wart.
Peter Dobcsanyi
dpeter at designtheory.org
Fri Mar 15 17:55:00 EST 2002
Bengt Richter <bokr at oz.net> wrote:
> I wonder how the proportions would change if len(ls)
> were 1,000,000 instead of 1,000
> and/or if you used xrange in place of range.
Good question, as it turned out.
I timed only the following methods:
def foo(ls, q):
for i in range(len(ls)):
if ls[i] == q:
return i
def xfoo(ls, q):
for i in xrange(len(ls)):
if ls[i] == q:
return i
def bar(ls, q):
i = 0
for x in ls:
if x == q:
return i
i += 1
If you have to go over (almost) the entire list then the proportions
don't really change.
len(ls) = 1000
search for "998"
repeat 3000 times
i in range(len(ls)): 2.02
i in xrange(len(ls)): 2.25
x in ls; i+=1 : 2.24
----------------------------------------------------------
len(ls) = 10000
search for "9998"
repeat 3000 times
i in range(len(ls)): 23.71
i in xrange(len(ls)): 25.04
x in ls; i+=1 : 25.44
----------------------------------------------------------
len(ls) = 100000
search for "99998"
repeat 3000 times
i in range(len(ls)): 212.83
i in xrange(len(ls)): 220.57
x in ls; i+=1 : 257.96
----------------------------------------------------------
But when the number of iterations over the list is small compared to the
length of the list then xrange and the counting methods obviously win.
In all cases below I have searched for '998'.
len(ls) = 1000
search for "998"
repeat 3000 times
i in range(len(ls)): 2.02
i in xrange(len(ls)): 2.26
x in ls; i+=1 : 2.28
----------------------------------------------------------
len(ls) = 10000
search for "998"
repeat 3000 times
i in range(len(ls)): 3.36
i in xrange(len(ls)): 2.19
x in ls; i+=1 : 2.27
----------------------------------------------------------
len(ls) = 1000000
search for "998"
repeat 3000 times
i in range(len(ls)): 22.40
i in xrange(len(ls)): 2.22
x in ls; i+=1 : 2.57
So it depends :-)
Peter
More information about the Python-list
mailing list