Sequence iterators with __index__

yaipa yaipa at yahoo.com
Fri Jun 27 14:30:42 EDT 2008


On Jun 24, 4:19 pm, schickb <schi... at gmail.com> wrote:
> On Jun 24, 3:45 pm, Matimus <mccre... at gmail.com> wrote:
>
>
>
> > > I think it would be useful if iterators on sequences had the __index__
> > > method so that they could be used to slice sequences. I was writing a
> > > class and wanted to return a list iterator to callers.  I then wanted
> > > to let callers slice from an iterator's position, but that isn't
> > > supported without creating a custom iterator class.
>
> > Could you post an example of what you are talking about? I'm not
> > getting it.
>
> Interactive mock-up:
>
> >>> a = ['x','y','z']
> >>> it = iter(a)
> >>> a[it:]
> ['x', 'y', 'z']
> >>> it.next()
> 'x'
> >>> a[it:]
> ['y', 'z']
> >>> a[:it]
> ['x']
> >>> it.next()
> 'y'
> >>> a[it:]
>
> ['z']
>
> This lets you use sequence iterators more general position indicators.
> Currently if you want to track a position and slice from a tracked
> position you must do it manually with an integer index. It's not
> difficult, but given that sequence iterators already do that already
> it seems redundant (and of course more error prone).
>
> > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/
>
> Ok thanks, but I do want some idea of interest level before spending a
> bunch of time on this.
>
> -Brad


Brad,

enumerate() seems to solve this problem for me....

>>
>> a = ['x','y','z']
>> ea = enumerate(a)
>> index, value = ea.next()
>> index
0
>> value
'x'
>> index, value = ea.next()
>> a[index:]
['y', 'z']
>>

putting this bit of code in a thin class wrapper should be useful to
keep the two data objects in sync. adding a reset() method allows you
to rebuild the enumerate object as often as needed.

Hope this helps.

  --Alan



More information about the Python-list mailing list