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

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Oct 30 11:13:15 CET 2013


On 30 October 2013 10:02, Paul Moore <p.f.moore at gmail.com> wrote:
>> 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.

Until you hit the bug where n is 0.

>>> a = 'abcde'
>>> for n in reversed(range(4)):
...     print(n, a[-n:])
...
3 cde
2 de
1 e
0 abcde

This is what I mean by the wraparound behaviour causing corner cases
and bugs. I and others have reported that this is a bigger source of
problems than the off-by-one negative stride issue which has never
caused me any actual problems. Yes I need to think carefully when
writing a negative stride slice but I generally need to think
carefully every time I write any slice particularly a multidimensional
one. The thing that really makes it difficult to reason about slices
is working out whether or not your code is susceptible to wraparound
bugs.

> 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).

But you currently need to write it that way to get the correct behaviour:

>>> for n in reversed(range(4)):
...     print(n, a[len(a)-n:])
...
3 cde
2 de
1 e
0


Oscar


More information about the Python-ideas mailing list