Why I think range is a wart.

Christian Tanzer tanzer at swing.co.at
Thu Mar 14 12:51:00 EST 2002


> > for index in range(len(mylist)):
> >     <whatever>
> >
> > and in the <whatever> body I need to make use of the indexes. I am not
> > sufficiently qualified to say if this is Pythonic or not, but I find
> > myself doing this quite often.
>
> It happens to me too, mostly when I'm using a sliding window
> type algorithm, that is, I need to look at two adjacent members
> of the list. You can't do this easily by iterating through the list;
> unrolling the first entry and the last entry are a pain.

I use a function pairwise to do such things:

    for l, r in pairwise(mylist) :
        <whatever>

Probably not as fast as index manipulation, but IMHO much easier to
read/write/understand.

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list