0

This might be a noob question but am not an expert in programming. I am having a hard time grasping the concept. Any help/explanation would be appriciated.

If str1 = 'hello' and we want to know str1[-1].

Shouldn't the answer be - out of bound/error and not 'o'? Why is it 'o'? Can anyone explain me the reason behind it? The book is very unclear about it.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Istiak Khan
  • 173
  • 2
  • 2
  • 10
  • I'm not 100% sure about the _reason_ why python allows negative numbers in slices, but if I had to guess I'd say it's because they're useful. – Aran-Fey Apr 30 '18 at 08:27
  • Thanks. Makes a lot more sense now. -1 was referring to the last item in the array of the string. – Istiak Khan Apr 30 '18 at 08:30
  • You can imagine the indices as a circular tape with numbers. 0 represents the first element, 1 the second and so on. If you look at the tape in the reverse order -1 is the last element, -2 the one before the last. example st = 'abcd' st[-1] = 'd' st[-2] = 'c' – Ale Apr 30 '18 at 09:45

0 Answers0