range(seq)?

Quinn Dunkan quinn at hurl.ugcs.caltech.edu
Fri Feb 8 20:33:00 EST 2002


On Fri, 8 Feb 2002 12:05:37 +0000 (UTC), Magnus Lie Hetland
<mlh at vier.idi.ntnu.no> wrote:
>I just had an idea... I'm sure there are others out there who don't
>particularly like the much-used (and necessary) expression
>range(len(seq))... One proposed solution is to make integers iterable,
>so one can do:
>
>  for x in len(seq): ...
>
>That is one way of doing it, of course (i'm not sure I'm all that fond
>of it, but that's another matter ;)
>
>Then it occurred to me that perhaps it could be done the _other_ way:
>
>  for x in range(seq): ...
>
>I.e. let range() take a sequence (or iterable) as an argument, and
>generate range(len(seq)). (I guess in mathematical terms, if one sees
>a sequence as a function, that domain(seq) would be more appropriate,
>but what the hey ;)
>
>Of course, we have the proposed indices(seq)... But by allowing
>range() to work on iterables, we wouldn't have to add another
>function. And I can't see any significant code breakages (but I'm sure
>there are some... :)

I've always thought that sequences should have a keys() method.  Then we could
replace range(len(seq)) with seq.keys().  The 'indices' generator would then
be spelled [].iterkeys().

It would make it easier to write functions that work on dicts and lists, where
I always wind up writing something like:

if hasattr(a, 'keys'):
    ks = a.keys()
else:
    ks = range(len(ks))
for k in ks:
    ...


I'm sure this has been suggested and rebuffed, though.



More information about the Python-list mailing list