Why I think range is a wart.

Tim Legant tim-dated-1016743233.4ed988 at catseye.net
Thu Mar 14 15:40:32 EST 2002


Peter Dobcsanyi <dpeter at designtheory.org> writes:

> Fredrik Lundh <fredrik at pythonware.com> wrote:
> > 
> > note that
> > 
> >    index = 0
> >    for item in mylist:
> >        <whatever>
> >        index += 1
> > 
> > is faster than
> > 
> >    for index in range(len(mylist)):
> >        item = mylist[index]
> >        <whatever>
> > 
> 
> Here is some timing with variations posted so far.
> 
>     i in range(len(ls)):              2.01
>     x in ls; i+=1 :                   2.59
>     lambda x:zip(range(len(x)), x):   3.86
>     Iter class:                      10.7

[...]

> def bar(ls):
>     i = 0
>     for x in ls:
>         if ls[i] == '998':
>             return i
>         i += 1

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

You already have ls[i] as x, which was the whole point of /F's post.


Tim




More information about the Python-list mailing list