Index: counting from zero, and from the end
Every character of a string has a position number called an index, and Python starts counting at zero. For text = "school", the first character text[0] is s, text[3] is o and the last, text[5], is l. Python also counts backwards from the end with negative numbers: text[-1] is the last character l, and text[-6] is the first, s. So negative numbering starts at -1 for the last character, it does not start at zero. The sheet shows both rows of numbers under the letters. If you ask for a position that does not exist, such as text[6] for a string of length 6, Python stops with an IndexError, which means the index is out of range. The last valid index is always the length minus one.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | s | c | h | o | o | l |
| 2 | 0 | 1 | 2 | 3 | 4 | 5 |
| 3 | −6 | −5 | −4 | −3 | −2 | −1 |
1text = "school" 2print(text[0]) 3print(text[3]) 4print(text[-1]) 5print(text[-6])
s o l s
1text = "school" 2print(text[6])
IndexError: the index is out of range
Take the string "garden". Draw the sheet with the letters, the numbers from 0 and the numbers from -6. Which letter is text[2]? Which letter is text[-2]? Which index would cause an IndexError?