[Python-ideas] Where did we go wrong with negative stride?
Nick Coghlan
ncoghlan at gmail.com
Mon Oct 28 14:00:18 CET 2013
On 28 Oct 2013 16:34, "Chris Angelico" <rosuav at gmail.com> wrote:
>
> On Mon, Oct 28, 2013 at 10:45 AM, Greg Ewing
> <greg.ewing at canterbury.ac.nz> wrote:
> > Neal Becker wrote:
> >>
> >> One thing I find unfortunate and does trip me up in practice, is that
> >> if you want to do a whole sequence up to k from the end:
> >>
> >> u[:-k]
> >>
> >> hits a singularity if k=0
> >
> >
> > I think the only way to really fix this cleanly is to have
> > a different *syntax* for counting from the end, rather than
> > trying to guess from the value of the argument. I can't
> > remember ever needing to write code that switches dynamically
> > between from-start and from-end indexing, or between
> > forward and reverse iteration direction -- and if I ever
> > did, I'd be happy to write two code branches.
>
> If it'd help, you could borrow Pike's syntax for counting-from-end
> ranges: <2 means 2 from the end, <0 means 0 from the end. So
> "abcdefg"[:<2] would be "abcde", and "abcdefg"[:<0] would be
> "abcdefg". Currently that's invalid syntax (putting a binary operator
> with no preceding operand), so it'd be safe and unambiguous.
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).
Cheers,
Nick.
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131028/f70cbd3b/attachment.html>
More information about the Python-ideas
mailing list