-1
str1 = "hello"
print(str1[-1])

The output of the program is o, but, shouldn't it give error as an output, as nothing exist at -1 index?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Curious
  • 9
  • 1
  • Strings, as sequences, can be indexed with negative numbers. `-1` signaling the last element, `-2` the second from last on so on. See the section on [Strings](https://docs.python.org/3/tutorial/introduction.html#strings) in the Python Tutorial. – Dimitris Fasarakis Hilliard Nov 17 '16 at 12:33

1 Answers1

0

Negative indices in Python means they are relative to the end of the sequence. Which means -1 will give you the last, and -2 the second last, etc.

Or, if you prefer, you can think of the string as circular:

  -3-2-1 0 1 2 3 4 5 6
...l l o h e l l o h e...
eigil
  • 465
  • 10
  • 17