range(seq)?

Oren Tirosh oren-py-l at hishome.net
Fri Feb 8 12:04:48 EST 2002


On Fri, Feb 08, 2002 at 12:05:37PM +0000, Magnus Lie Hetland 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 like it.  It makes much more sense for the range function to understand
container types than for integers to be iterable.  An integer is an atom, 
there is nothing 'in' it.  

> I.e. let range() take a sequence (or iterable) as an argument, and

The length of some iterables may not be known in advance without actually
stepping through them with .next(), but anything with a __len__ will do.

> 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... :)

range() currently takes an int, long, float or a class with an __int__ 
method.  Constructing a case where range(seq) does not raise a TypeError 
but would behave differently under this proposal would require a class with 
both both __len__ and __int__ methods returning different values.  This 
seems rather unlikely.

> So, why is this a stupid idea? (I'm sure it is...)

It's a stupid idea because people hate it when someone shows them a much 
simpler way to do something and makes them feel stupid for not thinking of 
it themselves and coming up with more complicated solutions instead...

	Oren





More information about the Python-list mailing list