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

Neil Cerutti horpner at yahoo.com
Thu Oct 4 14:23:31 EDT 2007


On 2007-10-04, Casey <Caseyweb at gmail.com> wrote:
> I've used [::-1] as a shorthand for reverse on several occasions, but
> it occurred to me yesterday I never really thought about why it
> works.  First, I checked out the documentation.
>
>>From section 3.6 of the Python Library Reference:
>
> "The slice of s from i to j with step k is defined as the
> sequence of items with index x = i + n*k such that 0 <= n <
> (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k
> and so on, stopping when j is reached (but never including j).
> If i or j  is greater than len(s), use len(s). If i or j are
> omitted or None, they become ``end'' values (which end depends
> on the sign of k). Note, k cannot be zero. If k is None, it is
> treated like 1."

You just have to choose the right value for the end arguments.
With k negative, the result might be:

  [-1:-len(s)-1:k]

I.e., from -1 (the last element) to one beyond the first element
(-len(s)-1). A negative index seems to be the only way to refer
to the element before the first element.

In that case the forumula given above does yield the reverse
sequence.

For example, for len(s) of 3, you get, you would get the
following sequence of indices:

  i = -1, j = -4, k = -1

  -1 + -1 = -2
  -1 + 2*(-1) = -3
  -1 + 3*(-1) = -4

-4 is equal to j, so the sequence ends with s[-3].

> From this, I would expect that x[::-1] would be identical to
> x[n:0:-1] (n and 0 being the "end" values, with the order
> switched due to the negative step value).  But the clause that
> "(but never including j)" means that x[n:0:-1] excludes the 1st
> element of x, x[0].  A quick test in ipython confirms that
> "abc"[3:0:-1] => "cb", not "cba". Changing the "end" value  to
> x[n:-1:-1] results in an empty string.

Your proposed sequence, x[n:0:-1] is half-open on the wrong end.
When k is -1 then j must also be negative. This is because
there's no way to refer to the element one before the first
element without using a negative index value for j.

-- 
Neil Cerutti



More information about the Python-list mailing list