iters on ints? (reducing the need for range/xrange)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Nov 9 20:30:38 EST 2001


On Fri, 09 Nov 2001 23:30:25 GMT, William Tanksley
<wtanksle at dolphin.openprojects.net> wrote: 

>What if slicing/indexing the "int" builtin resulted in a generator with
>the desired behavior?
>
>for x in int[10]:
>for x in int[1:11]:
>for x in int[1:11:2]:

Best proposal so far.

># now some hard ones
>for x in int[0:]: # all the natural numbers
>for x in int[0::2]: # all the even naturals
>for x in int[:0]: # illegal
>for x in int[:0:-1]: legal, all negative numbers

The negative steps are tricky.  The last one should be int[0::-1].

But what would x[a:b:-1] do if x is an iterator?  Maybe that's useful for a
"bidirectional iterator"?  A unidirectional iterator would raise exception
and say "no attribute 'prev'" and the like.

Actually, this makes sense: An interator is equivalent to the set of natural
numbers, and a bidirectional iterator is equivalent to set of integers.
One candidate would be a linked list.

It might be useful to abstract out the slicing objects itself, which is used
in NumPy arrays.  So 1:10:2 would be the syntax for creating a slicing
object. 

To enable steps of other integers, you'd need an optional argument in next

class someiterator:
    def next(self, step=1):
        ...

So x[a:b:c] would get its elements by something like

i = s = a
while i<b:
   x.next(s)
   s = c
   i += c

For negative c maybe it's reasonable to assume x.next(a) is equiv to
x.prev(-a).

>Wait -- a question.  Do slices act on generators?  That is, can I slice
>out every other item of a generator (as I just did above)?  If not, could
>that be added?  Once that's added, what's to stop me from annoyingly
>demanding to be able to slice out every 'n'th item (keeping the rest as
>part of the generated sequence)?  Such a thing would feed my hunger for an
>interesting prime # sieve...

What would be the semantics?  Is it iterate and discard, or simply jump?  

>Wait, I'm hearing a voice.  It tells me, "WRITE A PEP."

Well, go for it. :-)

Huaiyu




More information about the Python-list mailing list