Say I have x = 'abcde'
. If I write x[::]
I get 'abcde'
, If I write x[::2]
I get 'ace'
. So the spaces between the colons implies for the first space, "the start of the list" and for the second space "the end of the list". It's as if you were writing x[0:len(x)]
right?
Okay, so when I write x[::-1]
I get the list completely in reverse, i.e. 'edcba'
. So what are the equivalent values I could substitute in?
x[len(x)-1:0:-1]
won't work because the second space is not including that number, so I would get 'edcb'
and if I went x[len(x)-1:-1:-1]
it would simply do nothing because x[len(x)-1] == x[-1]
.
Yes, it will always work if I leave the colons in, my confusion comes is what does just having x[::]
actually doing, what values is it actually substituting? Because if it were always just "the start of the list and the end of the list" then there's no way it would work for x[::-1]
, it would simply print nothing, and if it somehow knows to reverse it, then what values is it putting because even if we didn't have the problem of not being able to terminate at the right place (i.e. can't put 0 in the middle space because that wouldn't be include but can't put -1 because that's the end of the list) we have the problem that it should still start at 0, i.e. we should have
aedcb
instead?
Can anyone shed light on the behind the scenes magic here?
Thank-you.
(Yes I googled for this, and tried to look it up in the docs and could find no explanation to this specific question)
edit: The answer to my question can be found in the non accepted answer of Understanding Python's slice notation, namely, https://stackoverflow.com/a/24713353/4794023.
Thanks guys