[Python-ideas] Where did we go wrong with negative stride?

Paul Moore p.f.moore at gmail.com
Wed Oct 30 11:02:48 CET 2013


On 30 October 2013 09:52, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> Firstly would it not be better to add slice.__reversed__ so that it would be
>
>     b = a[reversed(slice(i, j))]

This won't work, because reversed returns an iterator, not a slice object.

> Secondly I don't think I would ever actually want to use this over the
> existing possibilities.

Agreed, while my usage is pretty trivial, I would definitely use

    b = a[::-1]

over

    b = a[Slice(None, None, None, reversed=True)]

I could probably omit some of those None arguments, but I probably
wouldn't simply because I can't remember which are optional.

> There are real problems with slicing and indexing in Python that lead
> to corner cases and bugs but this particular issue is not one of them.
> The real problems, including the motivating example at the start of
> this thread, are caused by the use of negative indices to mean from
> the end.

However, being able to write

    last_n = s[-n:]

is extremely useful. I'm losing track of what is being proposed here,
but I do not want to have to write that as s[len(s)-n:]. Particularly
if "s" is actually a longer variable name, or worse still a calculated
value (which I do a lot).

Paul


More information about the Python-ideas mailing list