[Tutor] How does [::-1] work?
john at fouhy.net
Thu Jan 19 04:36:57 CET 2006
On 19/01/06, Intercodes <intercodes at gmail.com> wrote:
> I tried that expression in my intepreter and various other combination but
> still can't comprehend how the expression works. I could understand[:] ,
> [n:] or [:n] . But what meaning does it have in using two colons inside
> array index while slicing?. A concise explanation would suppress my
This is new in python 2.3 (?).
Basically, the syntax is [start:stop:step].
>>> import string
>>> string.lowercase[::2] # every second letter, starting with 0
>>> string.lowercase[1::2] # every second letter, starting with 1
If step is negative, you work backwards. eg:
>>> string.lowercase[20:10:-2] # letters 20, 18, 16, 14, 12
And if you omit the start or stop parameters, and step is negative,
then start defaults to the end of the list and stop to the beginning.
So string.lowercase[::-1] will step backwards, starting at the end and
finishing at the start.
More information about the Tutor