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

Bruce Leban bruce at leapyear.org
Sun Oct 27 21:38:31 CET 2013


On Sun, Oct 27, 2013 at 10:04 AM, Guido van Rossum <guido at python.org> wrote:

> "abcde"[::-1] == "edcba"
>
> as you'd expect, but there is no number you can put as the second bound to
> get the same result:
>
> "abcde"[:1:-1] == "edc"
> "abcde"[:0:-1] == "edcb"
>

This isn't really a negative stride issue. [x:y] is a half-open range ==
[x, y) in mathematical notation and therefore you need a value for y that
is one more. As others have pointed out there is a number you can put in
the second bound but it's not a valid index:

'abcde'[:-6:-1] == 'abcde'

But the same thing applies to positive strides:

'abcde'[::1] == 'abcde'[:5:1] == 'abcde'

And the only values you can replace 5 with that work are out of bounds as
well or the special value None. None represents both the left edge and the
right edge and if we deem that confusing slices could be modified to accept
-inf as representing the left edge and inf as representing the right edge.
Thus we'd have:

'abcde'[-inf:inf] == 'abcde'
'abcde'[inf:-inf] == ''


On Sun, Oct 27, 2013 at 12:23 PM, MRAB <python at mrabarnett.plus.com> wrote:

> The difference might be because the left end is at offset 0 but the
> right end is at offset -1.
>

If the left end was offset 1 and the right end was offset -1 then some of
the asymmetry goes away.

On Sun, Oct 27, 2013 at 1:02 PM, Ron Adam <ron3200 at gmail.com> wrote:

> And I've never liked the property where when counting down, and you pass
> 0, it wraps around.   (And the other case of counting up when passing 0.)
>
>
And then when you count down and it passes 0, you'd get an index error.

I'm *not* proposing we change how strings are indexed. I think that might
break a few programs. I'm just pointing out that you can't count from zero
in both directions and that introduces some weirdness.

--- Bruce
I'm hiring: http://www.cadencemd.com/info/jobs
Latest blog post: Alice's Puzzle Page http://www.vroospeak.com
Learn how hackers think: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131027/56416566/attachment-0001.html>


More information about the Python-ideas mailing list