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

Chris Angelico rosuav at gmail.com
Mon Oct 28 07:33:17 CET 2013


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.

ChrisA


More information about the Python-ideas mailing list