Mysterious Colons in Python Reverse
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.
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:
-
start
is defaulted to be0
ifstep
is positive, otherwise-1
-
end
is defaulted to belen(s)
, otherwise-len(s)-1
-
step
is defaulted to be1
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.
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!