# Why I think range is a wart.

Christopher A. Craig com-nospam at ccraig.org
Wed Mar 13 18:53:50 CET 2002

```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.

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.

To go from the information that is stored in the list (an ordered list
of elements, and the size of said list) to the information you need to
iterate through indicies (an ordered sequence of indicies valid for the
given list) you need to take the length of the list (N), and create a
new list of N integers from 0 to N-1.  'range(len(mylist))' says
precisely that.  I don't see how this is the least bit kludgey.

.keys() and .items() methods on lists seem odd to me.  That is
inforamtion that the list does not contain.  Sure it can easily be
generated given information the list does contain, but why can't the
programmer generate it himself from the same information?

--
Christopher A. Craig <com-nospam at ccraig.org>
Is Peal Better Than Python?
No, no.  Quicker, easier, more seductive.

```