-1

As we all know L[::-1] reverses L, no matter L is a list or a string

>>> l=[1,2,3]
>>> l[::-1]
[3, 2, 1]
>>> s
'abc'
>>> s[::-1]
'cba'
>>> 

But I wonder what the two colons mean. I know it goes from back to front using '-1' as step length, but can you explain in more depth? Thanks :D

Daming Lu
  • 316
  • 1
  • 5
  • 21

1 Answers1

0

inside [] in python, the language spec parses :s into slice objects.

you can either give it just the one :, or two. If you omit values, then they are treated specially (i.e. as end values).

It's described here

More in-depth:

When parsing a program, [] are treated differently from other parts of the code;

as seen here:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] sliceop: ':' [test]

in the python grammar

The bit that's important there is noting that the individual subscripts can either be ... or a single item (in this case test), or optional tests separated by :.

The point is though, that when you do use the : in there, it's translated into a slice object, which is just passed to the __getitem__ object method*.

How your object deals with the slice objects it gets passed is up to it's implementation of __getitem__. Try doing something like this:

class my_class(object):
  def __getitem__(*slices):
    print slices
    pass

c = my_class()
c[1]
c[1:2]
c[1:2:3]
c[:2]
c[::3]
c[1::3]
c[1, 1:, :2, ::3, 1:2, 1::3, object(), [1,2,3,4,5]]

Note that all that's happening is that the various objects you put inbetween the [] jsut get passed to the __getitem__ method. The only different between then and any other place in python, is that inside [] there is the additional parsing of the slice() shortcut syntax start:end:step.

*at least it is for any object you create. Soem of the builtins do it a little differently - i think for legacy reasons.

will
  • 10,260
  • 6
  • 46
  • 69