What does the syntax [::-1] really mean?

Casey Caseyweb at gmail.com
Thu Oct 4 16:58:05 EDT 2007


On Oct 4, 4:32 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> > the invariant that you are looking for is that for all non-negative a, b:
> >    x[a:b:1] reversed is x[-len(x)+b-1:-len(x)+a-1:-1]
>
> I should of course have said "all a, b in the range 0 <= a <= len(x) and 0
> <= b <= len(x)".

Thanks, again! I figured it out from Fred's and your initial posts.
IM(ns)HO, this is non-intuitive.

I would expect that the reverse of x[i,j,k] would be x[j,i,-k]; eg;
x[0:len(x):1] would be x[len(x):0:-1].  This representation is little
more than syntactic sugar for x[y for y in range(i,j,k)], with a -1
adjustment to i and j if k is < 0 (due to the way range operates) and
with appropriate boundary checking on i and j.  The default values for
i and j would become (0,len(x)), flopped for k < 0.

There may be a good (or not-so-good) reason this representation
wouldn't have worked or would have caused problems.  Or maybe it is
just personal preference.




More information about the Python-list mailing list