Why I think range is a wart.

Peter Dobcsanyi dpeter at designtheory.org
Fri Mar 15 06:17:39 EST 2002


Tim Legant <tim-dated-1016743233.4ed988 at catseye.net> wrote:
> No.  Your bar() function is broken and the test results invalid.  Try
> this instead:
> 
> def bar(ls):
>    i = 0
>    for x in ls:
>        if x == '998':
>            return i
>        i += 1

Oops, you are right! I fixed it and ran the test again.

3000 times, Python 2.2, Linux:

    i in range(len(ls)):             2.03
    x in ls; i+= :                   2.28
    lambda x:zip(range(len(x)), x):  3.76
    Iter class:                     10.18

10000 times:

    i in range(len(ls)):             6.68
    x in ls; i+=1 :                  7.55
    lambda x:zip(range(len(x)), x): 12.56
    Iter class:                     35.56

Interestingly, "range(len(ls))" is still faster.

    Peter



More information about the Python-list mailing list