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

Tim Peters tim.peters at gmail.com
Mon Oct 28 22:31:24 CET 2013


>> under the proposal we have:
>>
>>      s[i:j:k] == s[i:j][::k]

[Terry Reedy]
> 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).

I think that's right :-)

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

Right.

> I presume s[::-k], k a count, would continue to mean 'reverse and take every
> kth' (ie, take every kth item from the right instead of the left):

That's not what the proposal said, but it's a reasonable alternative.
Maybe that's better because it's "more compatible" with what happens
today.  The hangup for me is that I have no use cases for negative
strides other than -1, so have no real basis for picking one over the
other.  OTOH, since I _don't_ have any use cases, I don't care either
what happens then ;-)

> s[i:j:-k] == s[i:j:-1][::k]

That's a nice form of symmetry too.  Sold ;-)

> (And one would continue to write the alternative, 'take every kth and
> reverse' explicitly as s[i:j:k][::-1].)
>
> 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.

Yup!

> ---
> 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 think they all round down.  For example, Icon uses 1-based indexing,
and supports slicing.  "abc"[1] is "a" in Icon, and so is "abc"[1:2].
0 isn't a valid index in Icon, can be used in slicing, where it means
"the position just after the last element".

> String 'indexing' is really unit slicing: s[i] == s[i:i+1].  Any sequence
> can sliced.  True indexing requires that the members of the sequence either
> be Python objects (tuples, lists) or usefully convert to such (bytes, other
> arrays, which convert integer members to Python ints).


More information about the Python-ideas mailing list