Sub topic 4
When an index is out of range
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 also assumes you know that indexes start at 0 and that negative indexes count from the end.
The range of valid indexes
A string of length n accepts exactly two ranges of indexes:
0ton - 1, counting from the front.-nto-1, counting from the back.
Any integer outside both ranges raises IndexError. For "Python", n is 6, so the valid indexes are 0 to 5 and -6 to -1.
| Index | Valid for `"Python"`? | Result |
|---|---|---|
| `0` | Yes | `'P'` |
| `5` | Yes | `'n'` |
| `6` | No | `IndexError` |
| `-1` | Yes | `'n'` |
| `-6` | Yes | `'P'` |
| `-7` | No | `IndexError` |
Seeing the error
Run this to see the exact message:
s = "Python"
try:
s[6]
except IndexError as e:
print(e)It prints string index out of range. The same message appears for an index too far below zero, such as s[-7].
The off-by-one mistake
The most common cause is using len(s) as an index. The length is the number of characters, but the last valid index is one less, because counting starts at 0.
s = "Python"
n = len(s)
print(n)
print(s[n - 1])
print(s[-1])
try:
print(s[n])
except IndexError:
print("s[len(s)] is always out of range")This prints 6, n, n, and then the message from the except block. For the last character, s[-1] is clearer than s[len(s) - 1].
Loops cause the same mistake. If you write range(len(s) + 1) and index with the loop variable, the final pass uses len(s) and fails.
Empty strings
An empty string has length 0, so no index is valid. Both ""[0] and ""[-1] raise IndexError. This catches code that takes the first or last character of user input without checking that any input exists.
def first_char(text):
if not text:
return ""
return text[0]
print(repr(first_char("Python")))
print(repr(first_char("")))This prints 'P' and then ''. An empty string is falsy, so if not text is a short length check.
Choosing how to handle it
You have two reasonable options, and the choice depends on how often the bad index occurs.
- Check first. Compare the index to the length. This suits cases where an out-of-range index is common and expected, such as short inputs.
- Catch the exception. Wrap the access in
try/except IndexError. This suits cases where an out-of-range index is rare, and it keeps the normal path simple.
def char_at(text, i, default=None):
try:
return text[i]
except IndexError:
return default
print(char_at("Python", 2))
print(char_at("Python", 10, "?"))
print(char_at("Python", -7, "?"))This prints t, ? and ?.
A different error: wrong type
An index must be an integer. A float or a string fails with TypeError, not IndexError. This matters when an index comes from division, because / returns a float.
s = "Python"
middle = len(s) / 2
try:
s[middle]
except TypeError:
print(type(middle).__name__)
print(s[len(s) // 2])This prints float and then h. Use // for whole-number division when computing indexes.
Exercise
For s = "Python", which of these raise IndexError: s[5], s[6], s[-6], s[-7]? What does ""[-1] do?
Show answer
s[6] and s[-7] raise IndexError. The valid indexes are 0 to 5 and -6 to -1, so s[5] returns 'n' and s[-6] returns 'P'. ""[-1] also raises IndexError, because an empty string has no valid index.
Exercise
This function should return the last character of a string, but it fails on every input. Fix it so it works for non-empty strings. def last(text): return text[len(text)]
Show answer
Use the last valid index, len(text) - 1, or the shorter -1: def last(text): return text[-1]. The original uses len(text), which is one past the end.