Why I think range is a wart.

Bertrand Geston bergeston at yahoo.fr
Thu Mar 14 11:34:40 EST 2002


Thanks Christopher for your clear and intelligent response. I could only add
that it is always possible to use a dictionary with an ordered range of
integers as keys (or even as values). In some cases, it should probably make
sense.

Ironically, I could ask "why not add indices in the dictionary type, it is
sometimes usefull" ?

Let's keep things simple and understandable :
- lists are ordered sets,
- dictionnaries are "keyed" sets.

And if somebody needs something richer, just combine or inherit from those
types (btw many many thanks to the BDFL and his team for Python 2.2, for the
little that I know it, I really appreciate it).

B.

"Christopher A. Craig" <com-nospam at ccraig.org> wrote in message
news:mailman.1016042063.7531.python-list at python.org...
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.






More information about the Python-list mailing list