What is a negative index in Python and why is it used?
A negative index counts from the end of a sequence. -1 is the last item, -2 is the second last, and so on. Positive indexes start from 0 at the front.
letters = ["a", "b", "c", "d"]
print(letters[-1])
print(letters[-2])
text = "Python"
print(text[-3:])
print(text[:-1])
Output:
Tutorials Class - Output Window
d
c
hon
Pytho
It is useful because you can get the last items without knowing the length of the list. A common use is text[:-1] to remove the last character, for example a new-line at the end of a line. If the negative number is bigger than the length, Python raises an IndexError.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |