-2

I am very new to Python and I encountered one issue that I cannot understand. Let say I have string variable:

myVar = "abcdefgh"

I want to display it backward, no problem:

print(myVar[::-1])

and I get hgfedcba. Nothing surprising here. I should get the same with this somewhat verbose code:

print(myVar[len(myVar)-1:0:-1])

but this time the result is hgfedcb. Then I have tried not to subtract 1 from len(myVar) and the result was exactly the same. I do not understand why, especially that lines:

print(myVar[::1])
print(myVar[0:len(myVar):1])

display the same results.

So, my question is why print(myVar[len(myVar):0:-1]) does not display "a"?

MarcinSzaleniec
  • 2,246
  • 1
  • 7
  • 22

1 Answers1

0

The verbose equivalent of print(myVar[::-1]) would be:

print(myVar[-1:-1-len(myVar):-1])
# Or
# print(myVar[len(myVar)-1:-1-len(myVar):-1])
# but this makes the the length invariant less obvious

Note that the stop parameter is exclusive, and in order to get to the actual -1, you have to additionally subtract the full length as negative indexing starts at the end of the sequence. Note also how (stop-start)*step is still the length of the slice.

user2390182
  • 72,016
  • 6
  • 67
  • 89