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

MRAB python at mrabarnett.plus.com
Tue Oct 29 04:43:28 CET 2013


On 29/10/2013 01:34, Ron Adam wrote:
>
>
> On 10/28/2013 08:00 AM, Nick Coghlan wrote:
>> In this vein, I started wondering if it might be worth trying to come up
>> with a syntax to control whether the ends of a slice were open or closed.
>>
>> Since mismatched paren types would be too confusing, perhaps abusing some
>> binary operators as Chris suggested could help:
>>
>> "[<i:" closed start of slice (default)
>> "[i<:" open start of slice
>> ":>j]" open end of slice (default)
>> ":j>]" closed end of slice
>> ":>j:k]" open end of slice with step
>> ":j>:k]" closed end of slice with step
>>
>> Default slice: "[<0:-1>:1]"
>> Reversed slice: "[<-1:0>:-1]"
>>
>> This makes it possible to cleanly include the final element as a closed
>> range, rather than needing to add or subtract 1 (and avoids the zero trap
>> when indexing from the end).
>
> I think a reverse index object could be easier to understand.  For now it
> could be just a subclass of int.  Then 0 and rx(0) would be distinguishable
> from each other.  (-i and rx(i) would be too.)
>
>       seq[0:rx(0)]        Default slice.
>       seq[0:rx(0):-1]     Reversed slice.  (compare to above)
>
>       seq[rx(5): rx(0)]   The last 5 items.
>
>
> A syntax could be added later.  (Insert preferred syntax below.)
>
>       seq[\5:\0]           The last 5 items
>
If you're going to have a reverse index object, shouldn't you also have
an index object?

I don't like the idea of counting from one end with one type and from
the other end with another type.

But if you're really set on having different types of some kind, how about
real counting from the left and imaginary counting from the right:

     seq[5j : 0j] # The last 5 items

     seq[1 : 1j] # From second to second-from-last

>
>
> How about this example, which would probably use names instead of the
> integers in real code.
>
>       >>> "abcdefg"[3:10]       # 10 is past the end.  (works fine)
>       'defg'
>
> Sliding the range 5 to the left...
>
>       >>> "abcdefg"[-2:5]       # -2 is before the beginning?  (Nope)
>       ''                        # The wrap around gotcha!
>
> The same situation happens when indexing from the right side [-i:-j], and
> sliding the range to the right.  Once j >= 0, it breaks.
>
>
> It would be nice if these worked the same on both ends.  A reverse index
> object could fix both of these cases.
>
If you don't want a negative int to count from the right, then the
clearest choice I've seen so far is, IHMO, 'end':

     seq[end - 5 : end] # The last 5 items

     seq[1 : end - 1] # From second to second-from-last

I don't know the best way to handle it, but here's an idea: do it in
the syntax:

     subscript: subscript_test | [subscript_test] ':' [subscript_test] 
[sliceop]
     subscript_test: test | 'end' '-' test



More information about the Python-ideas mailing list