Why I think range is a wart.

Andrae Muys amuys at shortech.com.au
Wed Mar 13 20:24:51 EST 2002


Gon?lo Rodrigues <op73418 at mail.telepac.pt> wrote in message news:<tf6v8u40aqikddq19jfnugo7tm83v0gpo0 at 4ax.com>...
> On 13 Mar 2002 12:53:50 -0500, com-nospam at ccraig.org (Christopher A.
> Craig) wrote:
> 
> >Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:
> >
> >> For starters, range (and xrange) is a perfectly sensible, reasonable and
> >> useful built-in. But the biggest use I make of it is in iterating through
> >> a list, e.g. as in
> >> 
> >> 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.
> >
> >I don't understand how range is a reasonable and useful built-in if
> >this use is not.  
> 
> There are other useful, reasonable and sensible uses for the range
> built-in. My comment is that this particular use looks warty to me
> because any sequence, especially if it obeys the "list-protocol" (that
> is, it has methods like __getitem__, __setitem__, etc.) should be able
> to generate the indexes (or keys) of its members. Just like a
> dictionary.
> 
> >
> >If you have a list [2, 3, 5, 7, 11] and you want to iterate through it
> >you don't need range:
> >
> >for item in list: 
> >  <work on items>
> >
> >If, on the other hand, you want to iterate though the indicies of said
> >list rather than the items themselves you need to come up with some
> >way to generate a zero based list of integers up to one less than the
> >size of the list (i.e. a list of indicies).  When you create this list
> >you aren't doubling information that the list already has.  A list
> >does not contain a list of indicies into itself.  The list knows its
> >elements, in order, and how many elements it has.  From this you can
> >generate a list of indicies, but there are no 'keys' stored in a list
> >object like there are in a dictionary.
> 
> This is where I beg to disagree. If the elements are in order, as they
> are in a list, it is perfectly reasonable to ask, "you are a list,
> right? then hand me the indexes of your members." If the list has the
> keys in memory or not, that is an implementation issue.

I dissagree, if you want the indexes attached to their items, ask for
it

zip(range(len(lst)), lst)

If it's a large list, use xrange/xzip respectively.  I am curious what
sort of programs you are writing where you so regularly care what the
index of a list item is?  Such concerns are not in my experience.  If
I want an array I'll use an array, but if I'm using a list it's as a
sequence.

I honestly can't work out what the problem is.

Andrae Muys



More information about the Python-list mailing list