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

Robert Kern robert.kern at gmail.com
Mon Oct 28 13:12:28 CET 2013


On 2013-10-27 18:32, Guido van Rossum wrote:

> What are real use cases for negative strides?

The main use case is numpy, I would wager. Slicing a numpy array returns a view 
on the original array; negative-stride views work just as well as positive 
strides in numpy's memory model. Most other sequences copy when sliced, so 
reversed() tends to work fine for them.

In my experience, the most common use of negative strides is a simple reversal 
of the whole array by leaving out the bounds:

   a[::-stride]

I think I have done the following once (to clip the first `i` and last `j` 
elements and reverse, cleanly handling reasonable values of `i` and `j`):

   a[-j+len(a)-1:-i-len(a)-1:-stride]

But I think I tend to do this more often:

   a[i:-j][::-stride]

(Though really, this needs to start with `a[i:len(a)-j]`, to handle `j==0`, as 
others have pointed out. I run into that problem more commonly.)

Implementation issues aside, the intention is just easier to read and reason 
about with the last option. It doesn't take much experience to get a good 
feeling for what each of those simple operations do and how they would compose 
together. Combining them into one operation, no matter what syntax you pick, is 
just going to be harder to learn.

I don't think the language needs to change. The latter uses are pretty rare in 
my experience, and the last option is a good one. The amount of documentation 
you would need for any new syntax would be about the same as just pointing to 
the last option.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



More information about the Python-ideas mailing list