15

Possible Duplicate:
Good Primer for Python Slice Notation
reverse a string in Python

I've seen this syntax crop up in a few code snippets I've seen lately, and I'm curious as to what it does. If I have my_list = [1,2,3,4,5], and I execute my_list[::-1], I'm given a list with the elements reversed [5,4,3,2,1]. Could someone please explain to me what this actually does, and show the difference between [:] notation and [::]? Or at least refer me to a resource that does.

I'm sure if I had a good Python book it would be in there, but I don't. And it's impossible to search Google for something like this since the [::] gets ignored. Thanks!

Community
  • 1
  • 1
Nathan Jones
  • 4,904
  • 9
  • 44
  • 70
  • 2
    there are a lot of posts on this .. I once asked about the same and was told to search .. and found a bunch that explain it. – Levon Jun 22 '12 at 22:54
  • 1
    [This one for example](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) and [this one](http://stackoverflow.com/questions/766141/reverse-a-string-in-python?lq=1) – Levon Jun 22 '12 at 22:55
  • 3
    Incidentally, [SymbolHound makes searching for punctuation easy](http://symbolhound.com/?q=python+[%3A%3A]). Google rules at many things but programming is their weakest area by far... – sarnold Jun 22 '12 at 22:57

1 Answers1

34

There is no difference between [:] and [::].

But [::-1] does something else: it has a negative step parameter. The absence of the start and stop parameters means the complete array. The negative step parameter means that data is taken in reverse order, from the end to the start.

glglgl
  • 89,107
  • 13
  • 149
  • 217