What does the syntax [::-1] really mean?
Robert Kern
robert.kern at gmail.com
Thu Oct 4 13:07:53 EDT 2007
Casey 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."
>
>>From Section 5.3.3 of the Python Language Reference (x[::-1] is a
> "proper slice" in the BNF, hence the excerpt):
>
> "The conversion of a proper slice is a slice object (see section 3.2)
> whose start, stop and step attributes are the values of the
> expressions given as lower bound, upper bound and stride,
> respectively, substituting None for missing expressions."
>
> Following the reference to section 3.2 provides a (non-rigorous)
> description of what a slice object is, in terms of the extended
> slicing semantics. But it doesn't shed any additional light on the
> meaning of [::-1].
>
>>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.
>
> So my question is: "what exactly is [::-1] shorthand for"? Or is it a
> special case, in which case why isn't it defined as such in the
> library?
It's a shorthand for [None:None:-1].
I think you're misinterpreting the sentence, "If i or j are omitted or None,
they become ``end'' values (which end depends on the sign of k)." The end values
*aren't* 0 and n except by happenstance. None (or omission) is a special marker
that says "go to the end".
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list