Sub topic 3
Counting from the end with negative indexes
This chapter assumes you can run Python code in a REPL or script, assign a string literal to a variable, use print() and len(), and read a simple try/except block. It also assumes you know zero-based indexing from the previous chapter, where s[0] is the first character of s.
By the end you will be able to read characters from the end of a string with negative indexes. You will also be able to convert between negative and non-negative indexes, and avoid the common mistakes that come with them.
The idea: a second numbering from the right
A string has one set of characters but two ways to number them. Non-negative indexes start at 0 on the left. Negative indexes start at -1 on the right, so -1 is the last character, -2 is the one before it, and so on.
s = "Python"
print(s[0])
print(s[5])
print(s[-1])
print(s[-6])This prints P, n, n and P. Here s[5] and s[-1] name the same character, and so do s[0] and s[-6].
The table shows both numberings for "Python".
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Non-negative index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
Each column adds up to len(s) minus 0, that is, the negative index equals the non-negative index minus 6. The next section turns that observation into a rule.
Why negative indexes exist
Without them, you reach the last character with s[len(s) - 1]. That works, but it repeats the variable name and is easy to get wrong by one. s[-1] says what you mean: the last character.
Negative indexes also remove a dependency on the length. If you want "the last character" or "the second to last", the code stays the same whether the string has 3 characters or 3,000.
word = "Python!"
print(word[-1] == "!")
print(word[-2])This prints True and then n. Neither line needed to know that word has 7 characters.
The conversion rule
Python treats a negative index i as i + len(s). The result is then used as an ordinary zero-based index. This is the whole mechanism, and it explains every behavior in this chapter.
s = "Python"
n = len(s)
for i in (-1, -2, -6):
print(i, s[i], s[i + n])The output is:
-1 n n
-2 o o
-6 P PFor each negative index, s[i] and s[i + n] give the same character. You rarely write the addition yourself, but it is the right way to reason about a negative index when you are unsure what it points at.
The diagram shows that the range check happens after the shift. This ordering matters for the error cases below.
The valid range
For a string of length n, the valid indexes are -n through n - 1. That gives n positions from the left and n from the right, covering each character twice.
| Length | Smallest valid index | Largest valid index |
|---|---|---|
| 6 | -6 | 5 |
| 1 | -1 | 0 |
| 0 | none | none |
The last row is worth noting. An empty string has no valid index in either direction, so ""[-1] fails even though people often assume "last character" is always safe.
empty = ""
try:
empty[-1]
except IndexError as e:
print(e)This prints string index out of range. The conversion rule gives -1 + 0 = -1, which is still negative, so the range check fails.
Going too far on a non-empty string fails the same way:
s = "Python"
try:
s[-7]
except IndexError as e:
print(e)The index -7 becomes -7 + 6 = -1, which is not in 0 to 5. The message is again string index out of range. The next chapter looks at index errors in more detail. For now, remember that the error text does not say whether you went too far left or too far right.
Guarding against empty strings
Because text[-1] fails on an empty string, code that reads user input or file lines should handle that case. A common guard is a truthiness test, since an empty string is false.
def last_char(text):
if not text:
return ""
return text[-1]
print(repr(last_char("Python")))
print(repr(last_char("")))This prints 'n' and then ''. The function returns an empty string for empty input instead of raising an exception. Whether that is the right choice depends on your program. Sometimes you want the exception, because an empty value signals a bug upstream.
Gotcha: `-0` is not "the last character"
Negative numbering starts at -1, not -0. Since -0 is just 0 in Python, s[-0] is the first character.
s = "Python"
print(-0)
print(s[-0])This prints 0 and then P. The asymmetry exists because the right-hand numbering has to avoid colliding with 0, which already means the first character. Counting from the left starts at 0, and counting from the right starts at 1 with a minus sign.
This causes bugs when a loop variable is negated:
s = "Python"
for i in range(len(s)):
print(i, s[-i])The output is:
0 P
1 n
2 o
3 h
4 t
5 yThe author probably wanted the characters from the end, starting with n. Instead the first iteration gives P, and the loop never reaches the last-but-one correctly aligned with i. The fix is to shift by one:
s = "Python"
for i in range(len(s)):
print(i, s[-(i + 1)])This prints n, o, h, t, y, P in order. Here -(i + 1) runs from -1 down to -6, which is exactly the valid negative range.
Gotcha: computed negative indexes can wrap around
Negative indexes are legal, so a calculation that was meant to produce a position from the left can silently land on the right side. Suppose you compute a position by subtraction:
s = "Python"
position = 2 - 3
print(position)
print(s[position])This prints -1 and then n. No error is raised because -1 is a valid index. If the subtraction was supposed to mean "three steps before position 2, which doesn't exist", the code returns the wrong character without any warning.
When an index comes from arithmetic, check it before use if a negative value would be a bug:
def char_at(text, position):
if position < 0 or position >= len(text):
raise IndexError(f"position {position} is outside 0..{len(text) - 1}")
return text[position]
print(char_at("Python", 2))
try:
char_at("Python", -1)
except IndexError as e:
print(e)This prints t, then position -1 is outside 0..5. The function accepts only left-based positions and rejects everything else, which is the opposite of how a plain index behaves.
Negative indexes on other sequences
Lists and tuples follow the same rule, so [10, 20, 30][-1] is 30. This consistency is the reason the rule is worth learning once. Strings differ from lists in one respect that matters later: you cannot assign through a negative index, because strings are immutable. s[-1] = "x" raises TypeError, just as s[0] = "x" does.
Choosing between `s[-1]` and `s[len(s) - 1]`
| Situation | Prefer | Reason |
|---|---|---|
| You want the last or nth-from-last character | `s[-1]`, `s[-2]` | Shorter, no repeated variable, no length dependency |
| You are computing a position from the left | A non-negative index with a range check | Avoids silent wraparound |
| The string may be empty | A guard such as `if text:` | Both forms raise `IndexError` on empty input |
| You are looping over every character | `for ch in s:` | No index needed at all |
The last row is a reminder that indexes are not the first tool for visiting every character. Iterate directly when you can, and use indexes when you need a specific position.
Summary of rules
- A negative index
imeansi + len(s). - Valid indexes for length
nare-nthroughn - 1. -1is the last character.-0equals0, which is the first.- An empty string has no valid index, so
""[-1]raisesIndexError. - Arithmetic that produces a negative number does not fail by itself. It reads from the right end.
Exercise
Let s = "abcdef". What do s[-2] and s[-6] return, and what happens with s[-7]? Then explain what this loop prints first and why: for i in range(len(s)): print(s[-i]).
Show answer
s[-2] is 'e' because -2 + 6 = 4 and s[4] is 'e'. s[-6] is 'a' because -6 + 6 = 0. s[-7] becomes -1 after adding 6, which is out of range, so it raises IndexError with the message "string index out of range". The loop prints 'a' first because i is 0 and -0 equals 0, so s[-0] is s[0]. After that it prints 'f', 'e', 'd', 'c', 'b'.
Exercise
Write a function secondtolast(text) that returns the second-to-last character of a string, or None if the string has fewer than two characters. What does secondtolast("Python") return?
Show answer
def secondtolast(text): if len(text) < 2: return None return text[-2] secondtolast("Python") returns 'o'. The length check is needed because both "" and a one-character string have no valid index -2, so text[-2] would raise IndexError.