[Python-ideas] Where did we go wrong with negative stride?
Ron Adam
ron3200 at gmail.com
Tue Oct 29 02:34:29 CET 2013
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
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.
Cheers,
Ron
More information about the Python-ideas
mailing list