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

Kurt Smith kwmsmith at gmail.com
Thu Oct 4 13:41:23 EDT 2007


On 10/4/07, Casey <Caseyweb at gmail.com> wrote:
[snippage]
>
> 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.

Check it out:

>>> 'abc'[3:None:-1]
'cba'
>>>

The second argument to the slice object, if negative, will convert
this index to (len(x)+j), which is why 'abc'[3:-1:-1] == 'abc'[2:2:-1]
== ''.  If you pass in None for the 1st or second index, the slice
object will compute the right bounds based on the __len__ of the
object, and do the right thing.  When there is no value specified,
None is assumed.


>
> 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?

obj[::-1] == obj[None:None:-1] == obj[slice(None,None,-1)]

>>> 'abc'[::-1]
'cba'
>>> 'abc'[None:None:-1]
'cba'
>>> 'abc'[slice(None,None,-1)]
'cba'

Taking a look at the slice class:

 |  indices(...)
 |      S.indices(len) -> (start, stop, stride)
 |
 |      Assuming a sequence of length len, calculate the start and stop
 |      indices, and the stride length of the extended slice described by
 |      S. Out of bounds indices are clipped in a manner consistent with the
 |      handling of normal slices.

Kurt



More information about the Python-list mailing list