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

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Oct 29 00:18:08 CET 2013


On 28 October 2013 22:39, Terry Reedy <tjreedy at udel.edu> wrote:
> On 10/28/2013 4:20 PM, Oscar Benjamin wrote:
>
>> Also I'm not the only person to point out that a more common problem
>> is with wraparound when doing something like a[:n].
>
>
> I think it a mistake to think in terms of 'wraparound'. This implies to me
> that there is a mod len(s) operation applied, and there is not. A negative
> index or slice position, -n, is simply an abbreviation for len(s) - n.
> Besides being faster to write, the abbreviation runs about 3x as fast with
> 3.3.2 on my machine.

I realise that it doesn't use modulo arithmetic. As I said earlier I
would be able to find uses for the current behaviour if it did.
However it does wraparound in some sense when the sign changes.

> The trick works because Python, unlike some other languages, does not allow
> negative indexing from the start of the array.  If Python had required an
> explicit end marker from the beginning, conditional code would  be required
> if the sign were unknown. If Python gained one today, it would have to be
> optional for back compatibility.

(I don't know if I understand what you mean.) Have you ever written
code where you didn't know if you wanted to index from the start or
the end of a sequence? I haven't and I use slicing/indexing
extensively. I have to write conditional code to handle the annoyingly
permissive current behaviour. Things that should be an error such as
passing in a negative index don't produce an error so I have to check
for it myself.


Oscar


More information about the Python-ideas mailing list