[Tutor] What exactly is [::-1]?

Luke Paireepinart rabidpoobear at gmail.com
Thu Jul 26 08:23:55 CEST 2007


Dick Moores wrote:
> At 08:38 PM 7/25/2007, Luke Paireepinart wrote:
>> > I would like to know what exactly the index notation of [::-1] is, 
>> where
>> > it comes from and if there are other variants.
>> >
>> This is called list slicing.  Look into it to figure out what all this
>> stuff means.
>> I could send you a link but I'd just google 'python list slicing' to
>> find it, so I'll leave that as an exercise for the reader.
>
> I don't find Google of help with this. Could someone supply a link?
Wow, it was actually quite a bit harder to Google than I thought :)
well, some experimentation leads me to believe this is the syntax for 
list slicing:

x[ i : j ] slices from i to j
x[ i : ] slices from i to the end of the list
x[ : j ] slices from the beginning of the list to j
x[ : ] slices from the beginning of the list to the unspecified 
parameter (the end of the list)  in other words, you can use this to 
make a copy.
x[ : : ]  This seems to work the same as the above.
(note that in both cases, : and ::, the list is just a one-level-deep 
copy.  so the list [[1,2,3],[4,5,6]] can't be copied fully with this.)
however,
x[ : : k ] is a copy (same as above) that uses k as a step.
Here are some examples that should make it make sense.
 >>> x = [1,2,3,4,5,6,7,8,9]
 >>> x[::1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> x[::2]
[1, 3, 5, 7, 9]
 >>> x[::5]
[1, 6]
 >>> x[::-5]
[9, 4]
 >>> x[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]


To summarize, the negative/positiveness of this parameter k denotes 
whether the step is from beginning to end, or from end to beginning.
so if it's negative, the step will start at the last element, then step 
|k| toward the beginning, then grab that element ( if such an element 
exists) and proceed in this manner.

This is all gleaned from experimentation, so it shouldn't be taken as 
the Word.
HTH,
-Luke

>
> Dick Moores
>
>
>



More information about the Tutor mailing list