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

Steven D'Aprano steve at pearwood.info
Tue Oct 29 03:25:43 CET 2013


On Mon, Oct 28, 2013 at 05:06:09PM -0400, Terry Reedy wrote:
> On 10/28/2013 2:49 PM, Tim Peters wrote:
> 
> >under the proposal we have:
> >
> >     s[i:j:k] == s[i:j][::k]
> 
> I think where we went wrong with strides was to have the sign of the 
> stride affect the interpretation of i and j (in analogy with ranges). 
> The change is to correct this by decoupling steps 1. and 2. below. The 
> result is that i and j would mean left and right ends of the slice, 
> rather than 'start' and 'stop' ends of the slice.

Sorry Terry, your paragraph above is ambiguous to me. It sounds like you 
are saying that having slices work by analogy with range was a mistake. 
Are you suggesting to break the analogy between slicing and range? That 
is, range continues to work they way it currently does, but change 
slice?


> Whether selecting or replacing, this proposal makes the rule for 
> indicating an arithmetic subsequence to be:
> 
> 1. indicate the contiguous slice to work on with left and right 
> endpoints (left end i, right end j, i <= j after normalization with same 
> rules as at present);
> 
> 2. indicate the starting end and direction of movement, left to right 
> (default) or right to left (negate k);
> 
> 3. indicate whether to pick every member of the slice (k=1, default) or 
> every kth (k > 1), starting with the first item at the indicated end (if 
> there is one) and moving in the appropriate direction.

"pick every kth element" works for k=1 as well as k > 1, no need for a 
special case here. Every 1th element is every element :-)


> My quick take on slicing versus indexing. The slice positions of a 
> single item are i:(i+1). The average is i.5. Some languages (0-based, 
> like Python) round this down to i, others (1-based) round up to i+1.

I don't think it's helpful to talk about averaging or rounding the 
indexes. Better to talk about whether indexes are included or excluded, 
or whether the interval is open (end points are excluded) or closed (end 
points are included).

Ruby provides both closed and half-open ranges:

2..5 => 2, 3, 4, 5
2...5 => 2, 3, 4

(If you think that the choice of .. versus ... is backwards, you're not 
alone.) Ruby has no syntax for stride, but range objects have a step(k) 
method that returns every kth value.

http://www.ruby-doc.org/core-1.9.3/Range.html

 
-- 
Steven


More information about the Python-ideas mailing list