[Python-ideas] Where did we go wrong with negative stride?
Ron Adam
ron3200 at gmail.com
Tue Oct 29 18:49:40 CET 2013
On 10/28/2013 10:43 PM, MRAB wrote:
>> 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.
It would be possible to make it work both ways by having a direction
attribute on it which is set with a unary minus opperation.
seq[-ix(5): -ix(0)]
Positive integers would work normally too. Negative ints would just be to
the left of the first item rather than the left of the last item.
Just had a thought. In accounting negative numbers are often represented
as a positive number in parenthes.
seq[(5,):(0,)] Last 5 items.
Unfortunately we need the comma to define a single item tuple. :-/
But this wuold work without adding new syntax or a new type. And the ','
isn't that big of a deal. It would just take a bit of getting used to it.
Cheers,
Ron
> 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
I think this would work too, but it's not any different than the [\5:\0]
syntax example. Just a differnt spelling.
Your example could be done without adding syntax by an end class. Which is
effectivly the same as an index class.
Cheers,
Ron
More information about the Python-ideas
mailing list