Why I think range is a wart.

Fredrik Lundh fredrik at pythonware.com
Thu Mar 14 03:08:35 EST 2002


Daniel Dittmar wrote:

> # if whatever contains only refs to mylist [index]
> for element in mylist:
>     <whatever>
>
> # if you really need the index
> def listIndices (list):
>     return range (len (list))
>
> for index in listIndices (mylist):
>     <whatever>

note that

    index = 0
    for item in mylist:
        <whatever>
        index += 1

is faster than

    for index in range(len(mylist)):
        item = mylist[index]
        <whatever>

> # my favourite
> for index, element in IndexAndElement (mylist):
>     <whatever>

you might prefer that one, but it's perfectly possible that your
users might be a bit happier if you used the += variant...

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list