Sub topic 3
Counting from the end with negative indexes
This chapter assumes you can run Python code, assign a string to a variable, use print() and len(), and read a simple try/except block. It builds on zero-based indexing, where s[0] is the first character.
The idea
A negative index counts backward from the end of the string. -1 is the last character, -2 is the second to last, and so on. You don't need to know the length of the string to reach its end.
s = "Python"
print(s[-1])
print(s[-6])
print(s[5])
print(s[0])This prints n, P, n and P. Each character has two valid indexes, one counted from the front and one from the back.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
The rule behind it
Python converts a negative index by adding the length of the string. For a string s, the expression s[-k] means the same as s[len(s) - k].
s = "Python"
print(len(s))
print(s[-1] == s[len(s) - 1])
print(s[-6] == s[len(s) - 6])This prints 6, True and True. The two spellings are equivalent, but the negative form is shorter and avoids repeating the variable name. That matters when the string comes from a longer expression.
Why it is useful
The most common use is reading the last character without computing the length.
filename = "report.txt"
print(filename[-1])
print(filename[-2])
path = "/home/user/"
if path[-1] == "/":
print("path ends with a slash")The output is t, x and path ends with a slash. Without negative indexes you would write filename[len(filename) - 1] every time.
Details to remember
- The smallest valid negative index is
-len(s), which is the first character. -0is the same number as0, sos[-0]returns the first character, not the last. This surprises people who expect-0to mean "the end".- Negative indexing works the same way on any string, including strings built at run time.
s = "Python"
print(s[-0])
print(s[-len(s)])This prints P twice.
A common error
A negative index can still be out of range. The valid range is -len(s) to -1. An index beyond that raises IndexError, just like a too-large positive index. The most frequent cause is an empty string, which has no last character.
def last_char(text):
try:
return text[-1]
except IndexError:
return None
print(last_char("Python"))
print(last_char(""))This prints n and None. For "", len is 0, so there is no valid index at all, positive or negative. If your input can be empty, check it first or catch the error. The next chapter looks at index errors in more detail.
Summary
Negative indexes give a direct path to the end of a string. Remember the conversion s[-k] == s[len(s) - k] and the valid range of -len(s) to -1. Slicing, which comes later, uses the same conversion for its bounds.
Exercise
Let s = "tutorial". What does s[-2] return, which positive index points to the same character, and what happens with s[-9]?
Show answer
s[-2] returns 'a'. The length is 8, so -2 becomes 8 - 2 = 6, and s[6] is also 'a'. s[-9] raises IndexError, because the smallest valid negative index is -8.