Sub topic 4
When an index is out of range
This chapter assumes you can run Python code in a script or REPL, assign string literals to variables, use print() and len(), and read a simple try/except block. It also assumes you know how zero-based and negative indexes address characters. Here you will learn exactly which indexes are valid, what happens when you use an invalid one, and how to guard against the error.
The valid range of indexes
A string of length n has exactly two valid ranges of indexes, and they describe the same characters.
- Non-negative indexes run from
0ton - 1. - Negative indexes run from
-nto-1.
Any integer outside -n to n - 1 is out of range. Python does not wrap around, round to the nearest valid index, or return a blank. It stops with an exception.
| Index | `0` | `1` | `2` | `3` | `4` | `5` |
|---|---|---|---|---|---|---|
| Character | `P` | `y` | `t` | `h` | `o` | `n` |
| Negative index | `-6` | `-5` | `-4` | `-3` | `-2` | `-1` |
For "Python", len(s) is 6. The valid indexes are 0 through 5 and -6 through -1. The first and last characters can be reached either way.
s = "Python"
print(s[0])
print(s[5])
print(s[-1])
print(s[-6])This prints P, n, n, P. Both ends are covered by two valid spellings.
What IndexError looks like
When you use an index outside the valid range, Python raises IndexError. It is a built-in exception that signals a sequence index outside the allowed range.
s = "Python"
try:
s[6]
except IndexError as e:
print(e)This prints:
string index out of rangeThe message does not say which index you used or how long the string was. If you need that detail while debugging, build it yourself from len() and the index you tried.
The error is raised for the negative side too. For "Python", s[-7] fails because the smallest valid negative index is -6.
s = "Python"
for i in (6, -7):
try:
s[i]
except IndexError as e:
print(i, "->", e)Both lines print string index out of range.
Why the boundary is where it is
The last valid index is n - 1, not n, because counting starts at 0. The most common source of IndexError is an off-by-one mistake, where code uses len(s) as if it were an index.
s = "Python"
try:
print(s[len(s)])
except IndexError as e:
print("Error:", e)
print(s[len(s) - 1])s[len(s)] fails because len(s) is 6, one past the last valid index. s[len(s) - 1] works and gives n. In practice s[-1] is clearer than s[len(s) - 1], and it cannot be off by one.
Empty strings have no valid index
An empty string has length 0. The valid non-negative range 0 to -1 is empty, and so is the negative range 0 to -1. This means every index fails, including 0 and -1.
s = ""
for i in (0, -1):
try:
s[i]
except IndexError as e:
print(i, "->", e)This matters in practice. Code such as name[0] to get a first initial works for every non-empty name and crashes on the empty string, often when a user leaves a form field blank.
Only integers are valid indexes
An index must be an integer, or an object that provides an integer through __index__. A float fails with a different error, TypeError, not IndexError. The distinction matters when you write except clauses.
s = "Python"
try:
s[1.0]
except TypeError as e:
print(e)This prints string indices must be integers, not 'float'. A common way to hit this is computing a middle position with /, which returns a float, instead of //, which returns an integer.
s = "Python"
middle = len(s) // 2
print(s[middle])This prints h, the character at index 3. Using len(s) / 2 would give 3.0 and raise TypeError.
Ways to handle an out-of-range index
There are four common approaches. The right one depends on whether an out-of-range index is a bug or an expected case.
Check the length first
Compare the index to the length before using it. This is the "look before you leap" style.
def char_at(text, i):
if -len(text) <= i < len(text):
return text[i]
return None
print(char_at("Python", 2))
print(char_at("Python", 10))
print(char_at("Python", -6))
print(char_at("", 0))This prints t, None, P, None. The chained comparison -len(text) <= i < len(text) states the valid range exactly, and it works for both positive and negative indexes.
Catch the exception
Use try/except when failure is unusual and you want the common path to stay simple. This is the "ask forgiveness" style.
def first_char(text):
try:
return text[0]
except IndexError:
return ""
print(first_char("Python"))
print(repr(first_char("")))This prints P and ''. Catch IndexError specifically. A bare except: would also hide unrelated errors, such as a TypeError from a wrong argument type.
Use a slice instead of an index
A slice never raises IndexError for out-of-range bounds, which a later chapter covers in detail. A one-character slice returns the character when it exists and an empty string when it does not.
s = "Python"
print(repr(s[0:1]))
print(repr(""[0:1]))
print(repr(s[:1]))
print(repr(""[:1]))This prints 'P', '', 'P', ''. The expression text[:1] is a compact way to get the first character of a string that might be empty. Likewise text[-1:] gives the last character, or an empty string.
The trade-off is that you cannot tell "no character" from "the character was an empty string", though a single character is never empty, so here the result is unambiguous. The result is also a string of length 0 or 1, not a missing value, so test it with if result: or if not result:.
Use string methods that do not index
Some tasks do not need an index at all. str.startswith() and str.endswith() answer common questions about the first and last characters, and they work on empty strings.
s = ""
print(s.startswith("P"))
print(s.endswith("n"))
print("Python".startswith("P"))
print("Python".endswith("n"))This prints False, False, True, True.
Choosing an approach
| Situation | Best choice | Reason |
|---|---|---|
| Out-of-range is a bug | Plain indexing, let it raise | The traceback points to the faulty code |
| Out-of-range is an expected input case | Length check or slice | No exception for normal flow |
| Out-of-range is rare | `try`/`except IndexError` | Keeps the common path simple |
| You only test the first or last character | `startswith` / `endswith` | No index arithmetic to get wrong |
Letting the error propagate is often correct. If a function requires a non-empty string, an IndexError during development reveals the broken caller. Silently returning a default can hide that problem.
Common mistakes
- Using
len(s)as an index. The last valid index islen(s) - 1. Uses[-1]instead. - Indexing an empty string.
""[0]and""[-1]both raise. Check for emptiness or usetext[:1]. - Looping with the wrong bound.
range(len(s) + 1)produces one index too many. Userange(len(s)), or better, loop over the characters directly withfor ch in s. - Forgetting the negative limit.
s[-7]on a six-character string fails just likes[6]. - Using
/for positions. Division produces a float and raisesTypeError, notIndexError. - Catching too much. A bare
except:hides real bugs. NameIndexError.
The loop mistake is easy to see in code.
s = "abc"
try:
for i in range(len(s) + 1):
print(i, s[i])
except IndexError as e:
print("stopped:", e)This prints 0 a, 1 b, 2 c, and then stopped: string index out of range when i reaches 3.
Reading the traceback
If you do not catch the exception, Python prints a traceback that ends with the line number and the exception type. A typical one looks like this:
Traceback (most recent call last):
File "example.py", line 2, in <module>
print(s[6])
IndexError: string index out of rangeRead it from the bottom. The last line names the exception. The line above it shows the code that failed. To find the cause, print len(s) and the index just before that line, or inspect them in a debugger. The failing index is usually computed from something else, such as a counter, a search result, or len().
A search result is a frequent source. str.find() returns -1 when nothing is found, and -1 is a valid index for a non-empty string. That means a failed search can silently select the last character instead of raising an error.
s = "Python"
pos = s.find("z")
print(pos)
print(s[pos])This prints -1 and then n. No error occurs, and the result is wrong. Always test pos != -1 before using it as an index. str.index() raises ValueError instead of returning -1, which is safer when absence is a bug.
Exercise
A function receives a string word and must return its last character, or an empty string if word is empty. Write the function in a way that never raises IndexError, then say what last_char("") and last_char("hello") return.
Show answer
One solution is def last_char(word): return word[-1:]. A slice does not raise on out-of-range bounds, so for "" it returns '', and for "hello" it returns 'o'. An equivalent version is def last_char(word): return word[-1] if word else "", which checks for emptiness first.
Exercise
For the string s = "tutorial", list the smallest and largest valid indexes (negative and non-negative), and say which of these raise IndexError: s[8], s[-8], s[-9], s[7].
Show answer
The length is 8, so valid indexes run from 0 to 7 and from -8 to -1. s[8] and s[-9] raise IndexError. s[-8] returns 't' and s[7] returns 'l'.