What does the syntax [::-1] really mean?
duncan.booth at invalid.invalid
Thu Oct 4 22:18:37 CEST 2007
Casey <Caseyweb at gmail.com> wrote:
> 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. 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
You made a mistake thinking that the first omitted value maps to 'n': in
fact it maps to -1.
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]
x[::1] is equivalent to x[0:len(x):1]
therefore x[::-1] is the same as:
which is just:
More information about the Python-list