0
string = "ABCDEFGH"

Can anyone explain why in string[start:end:stride] the start always starts from 0 while end starts with 1.

For example string[0:3:1] outputs the result as "ABC". As you can see I said end = 3 so shouldn't the string[0:3:1] be "ABCD" because computer read 0 first?

And one more thing why: I don't get a result for string[0:8:-1]. Shouldn't it be "HGFEDCBA"? I don't know if it is wrong syntax or not but I can print the result of string[::-1].

armatita
  • 12,825
  • 8
  • 48
  • 49
Noobrammer
  • 41
  • 3
  • 2
    Because `start` is included and `end` is not included. This way, `end - start` will give you the length of the slice. When you have a `list` of length `n`, `list[n]` is out of range, the last element will be `list[n-1]` – Will Apr 18 '16 at 19:42
  • Thank you all now it make sence. – Noobrammer Apr 19 '16 at 13:32

1 Answers1

0

Since len(string)=8, the slice string[0:8] is interpreted as "all memory indices 0-7" (i.e. 8 total indices). The last index in python is "up to but not including".

For the second part of your question, the syntax is string[7::-1]. string[0:8:-1] starts at 0 and tries to increment "backward", but since it has already reached "0" at the beginning of the iteration, no traversal occurs.

Sean McVeigh
  • 569
  • 3
  • 18