slicing return iter?

Raymond Hettinger python at
Sun Oct 18 03:09:21 CEST 2009

> > > sometimes I want to iterate a part of a sequence. but don't want to
> > > copy it. i.e.
 . . .
> I had checked it for serval times. maybe it's my inattention :-(. but
> what i could find the nearest thing is itertools.islice. but it can't
> process negative index -- that's supported by slice. so I need
> something, bind object with slice, and return a iter. I can find
> anything like it...:-(

If it really is a sequence (with len and getitem), you can write your
own indexing iterator:

  def myslice(seq, start, stop, step):
       'Allow forward or backwards iteration over a subslice'
       for i in range(start, stop, step):
           yield seq[i]


More information about the Python-list mailing list