s = [0, 1, 2, 3, 4]
print(s[::-1])

Print a reversed list

I am sure you have seen something like s[::-1] before, if you have ever used Python. You may have known that it means the reverse of s as a list. But why does it look like this? What do the two colons and the minus 1 mean?

Lots of people are using this syntax everyday, but I bet not every one of them knows what it really means. Therefore, I decide to write this blog to elaborate on this.

Let’s go back one step, to first look at the syntax of looping over a list.

s = [0, 1, 2, 3, 4]
start = 1
stop = 3
step = 1
print(s[start:stop:step])

Print a looped-over list

In the code above, start means the starting index(inclusive), stop means the ending index(exclusive), and step mean the step. Therefore, the code above will print out elements from index 1 to index 2, i.e., [1, 2].

You may have noticed the similarity between s[start:stop:step] and s[::-1]. YES! You guess it right. That’s where s[::-1] comes from! One more word about default values:

  1. start is defaulted to be 0 if step is positive, otherwise -1

  2. end is defaulted to be len(s), otherwise -len(s)-1

  3. step is defaulted to be 1

In s[::-1], start is left empty and -1 by default, end is left empty and -len(s)-1 by default, and step is assigned -1. A negative sign means the loop goes backward, and thus -1 means going back from the last element to the first element, one by one. We can also fully specify start, end and step. As expected, the result is the same as seen below.

s = [0, 1, 2, 3, 4]
start = -1
stop = -(len(s)+1)
step = -1
print(s[start:stop:step])

Print a reversed list with parameters

Bingo! So now you see how the mysterious two colons work in reversing a list. Well, Python has many more neat features just like this, which we are using everyday without thinking too much of how it works. Honestly, I am that type of person (LOL). But now I think I would give it a try, to relook at what I think I am familiar with, and learn the core of it. To have a better grasp of it, would mean I would make better of it in the future.

Stay tuned and see you next time!