[Python-ideas] Where did we go wrong with negative stride?
Tim Peters
tim.peters at gmail.com
Tue Oct 29 05:39:18 CET 2013
...
[Tim]
> Do you have a specific example of a currently-working slice assignment
> that couldn't easily be done under proposed alternatives?
[Andrew Barnert]
> s[:-4:-2]=1, 2
>
> This replaces the last and antepenultimate elements, whether s is even or
> odd.
> I suppose you could mechanically convert it to this:
>
> s[-mid+2::2]=reversed((1,2))
>
> But I don't know that I'd call that "easy".
Under my & Terry's proposal, it would be written
s[-3::-2] = 1, 2
And, at least to me, it's far more obvious this way that it affects
(all and only) s[-1] and s[-3]. It's immediate from "OK, s[-3:] is
the last three elements, so only those can possibly be affected. Then
the stride -2 skips the one in the middle, and picks on the last
element first."
Analyzing the current spelling is a royal PITA. "OK, umm, ah! The
stride is negative, so the empty part at the start refers to the last
element of the sequence. Then the second bit is -4, which is one
larger then we'll actually go. Oops! No, the stride is negative
here, so -4 is one *smaller* than we'll actually go. It will stop at
-4+1 = -3. I think." ;-)
> The question is whether this is realistic code anyone would ever
> intentionally write.
Obviously so, whenever they need to replace the last element element
with 1 and the antepenultimate element with 2 ;-)
BTW, do you know of any real code that uses a negative stride other
than -1? Still looking for a real example of that.
More information about the Python-ideas
mailing list