slicing return iter?

Raymond Hettinger python at rcn.com
Sun Oct 18 21:07:40 EDT 2009


[Raymond]
> > 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]

[StarWing]
> Thank you. but it can't support negative index :-(

The negative index is handled by the line, "yield seq[i]".

>>> s[-2:-5:-1] == ''.join(myslice(s, -2, -5, -1))
True
>>> s[-5:-2:1] == ''.join(myslice(s, -5, -2, 1))
True


Raymond






More information about the Python-list mailing list