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?
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?
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...