Sub topic 7
Slices That Go Past the Ends
What this chapter assumes
You should already know how to read one character with a positive or negative index. You should know that s[start:stop] includes start and excludes stop. You should also be comfortable with len(), print(), and a simple try/except block.
This chapter covers what happens when a slice bound lies outside the string. In short, an out-of-range index raises IndexError, but an out-of-range slice quietly adjusts its bounds and returns whatever fits. That is convenient, and it also hides some bugs. Knowing the exact adjustment rules lets you predict results and spot the hidden bugs.
Indexes raise, slices clamp
A string of length 6 has valid indexes 0 to 5 and -6 to -1. Asking for anything else with a single index fails:
s = "Python"
try:
s[6]
except IndexError as e:
print(e)A slice with the same out-of-range number does not fail:
s = "Python"
print(s[2:100])
print(repr(s[10:]))
print(repr(s[3:1]))This prints thon, then '', then ''. The last two are empty strings. repr() is used so the empty results are visible.
The reason is a design choice. A single index must name one character, and if no character exists there is no sensible value to return. A slice describes a range, and the part of a range that lies outside the string can simply contain nothing. The result of a slice is always a string, possibly an empty one.
How bounds are adjusted
Python resolves a slice in two steps. It first turns each bound into a concrete position. Then it collects the characters between those positions. For a positive step, which is the default, the resolution rules are:
- A missing
startbecomes 0, and a missingstopbecomeslen(s). - A negative bound has
len(s)added to it. So-2on a length-6 string becomes 4. - If a bound is still negative after that, it becomes 0.
- If a bound is greater than
len(s), it becomeslen(s). - If the resolved
startis greater than or equal to the resolvedstop, the result is empty.
You can watch these rules run with slice.indices(), which returns the resolved (start, stop, step) for a given length. Slice objects are covered in a later chapter. Here the method is used only to show the result of the rules:
s = "Python"
n = len(s)
for sl in [slice(2, 100), slice(10, None), slice(3, 1), slice(-100, 3), slice(-100, 100)]:
print(sl, sl.indices(n), repr(s[sl]))The output is:
slice(2, 100, None) (2, 6, 1) 'thon'
slice(10, None, None) (6, 6, 1) ''
slice(3, 1, None) (3, 1, 1) ''
slice(-100, 3, None) (0, 3, 1) 'Pyt'
slice(-100, 100, None) (0, 6, 1) 'Python'Compare the second row. A start of 10 is clamped down to 6, and the default stop is 6, so the range is empty. In the third row nothing is clamped, but start (3) is past stop (1), so nothing is selected.
Three ways to get an empty string
An empty result is the normal outcome of a slice with nothing to select. It comes from one of three situations:
| Situation | Example on `"Python"` | Resolved range |
|---|---|---|
| `start` is at or past the end | `s[10:]` | 6 to 6 |
| `start` is not before `stop` | `s[3:1]`, `s[3:3]` | 3 to 1, 3 to 3 |
| Both bounds clamp to the same end | `s[-100:-50]` | 0 to 0 |
An empty string is falsy, so if not s[a:b]: is a reasonable test for "nothing selected". No exception is raised in any of these cases, so a program will not warn you that a bound was off.
A negative step clamps differently
With a negative step the walk goes from right to left, so the clamping limits change. After a negative bound has len(s) added, the valid range for a bound is -1 to len(s) - 1. The value -1 means "one position before index 0", which is how a backward slice can run past the first character. The defaults also flip: a missing start becomes len(s) - 1, and a missing stop becomes that "before the beginning" position.
s = "Python"
n = len(s)
for sl in [slice(100, None, -1), slice(None, 100, -1), slice(-100, None, -1)]:
print(sl.indices(n), repr(s[sl]))This prints:
(5, -1, -1) 'nohtyP'
(5, 5, -1) ''
(-1, -1, -1) ''Read each line like this:
s[100::-1]starts too far right, so the start clamps to index 5 and the whole string is walked backward.s[:100:-1]has astopthat clamps to 5, which equals the start, so nothing is selected.s[-100::-1]has astartthat clamps to the position before the beginning. There is nowhere left to walk, so the result is empty.
The same words "too large" and "too small" produce opposite results depending on which bound and which direction you use. When you are unsure, call indices() and read the numbers.
The `-1` stop trap
The most common mistake with backward slices is using -1 as a stop to mean "through the first character". Rule 2 turns -1 into len(s) - 1, which is the last index:
s = "Python"
print(repr(s[5:-1:-1]))
print(repr(s[5:None:-1]))
print(repr(s[4:0:-1]))
print(repr(s[4::-1]))The output is '', 'nohtyP', 'ohty', 'ohtyP'. In the first slice, -1 resolves to 5, so the start and stop are equal and the slice is empty. The stop is excluded, so s[4:0:-1] stops before index 0 and loses the P. To include index 0 when walking backward, leave the stop out or pass None.
Computed bounds that go negative
Clamping is friendly with fixed numbers and risky with computed ones. If a bound is calculated and can drop below zero, the negative-index rule wraps it around to the end of the string instead of clamping to 0. This code tries to take up to three characters before position i:
s = "Python"
def before(text, i):
return text[i - 3:i]
print(repr(before(s, 5)))
print(repr(before(s, 2)))The first call prints 'tho'. The second prints '', though 'Py' was probably intended. For i = 2, the start is -1, which becomes 5, and 5 is not less than 2. The program raises no error and just returns the wrong answer. Clamp the computed bound yourself:
s = "Python"
def window(text, center, radius):
start = max(center - radius, 0)
return text[start:center + radius + 1]
print(window(s, 1, 2))
print(window(s, 5, 2))This prints Pyth and hon. The max(..., 0) stops the start from wrapping. The upper bound needs no guard, because an oversize stop is clamped to the end of the string.
Where clamping helps
Clamping removes the need for length checks in several common tasks:
- Truncating to a limit.
text[:20]works for any string, including ones shorter than 20 characters. - Reading the first or last character of a string that may be empty.
s[:1]ands[-1:]return''on an empty string, whiles[0]ands[-1]raiseIndexError. - Pagination or chunking. Taking
items[i:i + size]in a loop works even when the final chunk is short.
def preview(text, limit=10):
return text[:limit]
print(repr(preview("Hello")))
print(repr(preview("A much longer sentence")))
print(repr(""[:1]))The output is 'Hello', 'A much lon', and ''.
Bound types still matter
Clamping applies to integer values only. A bound must be an integer, None, or an object that provides __index__. A float such as 1.0 raises TypeError, even though the number looks fine. Convert with int() or use // for integer division when computing bounds.
Summary of the rules
- An index outside
-len(s)tolen(s) - 1raisesIndexError. - A slice bound outside that range is clamped, and the slice returns the characters that remain.
- With a positive step, negative bounds get
len(s)added, then are limited to the range 0 tolen(s). - With a negative step, bounds are limited to the range -1 to
len(s) - 1. - A slice whose resolved start does not come before its stop (in the direction of the step) is empty.
- A bound that is computed and can go negative wraps instead of clamping, so guard it with
max(..., 0).
Exercise
For s = "Python", predict the result of each expression: s[-100:2], s[4:100], s[100:], s[:100:-1], and s[5:-1:-1]. Then say which of these would raise an error if the slice were replaced by a single index of the same out-of-range number.
Show answer
s[-100:2] is 'Py' (the start clamps to 0). s[4:100] is 'on' (the stop clamps to 6). s[100:] is '' (start clamps to 6, which equals the stop). s[:100:-1] is '' (with a negative step the stop clamps to 5, equal to the start). s[5:-1:-1] is '' because -1 resolves to 5, so start and stop are equal. None of the slices raise an error. The single indexes s[-100], s[4:100] has no index equivalent, but s[100] and s[-100] would each raise IndexError because they are outside -6 to 5.
Exercise
Write a function last_chars(text, n) that returns the last n characters of text, or the whole string if it has fewer than n characters, and returns '' when n is 0. Explain why text[-n:] alone is wrong for n = 0.
Show answer
def lastchars(text, n): return text[len(text) - n:] if n > 0 else ''. The version text[-n:] fails for n = 0 because -0 is 0, so the slice becomes text[0:] and returns the whole string. For n larger than the length, text[-n:] is fine, since a start below -len(text) clamps to 0 and the whole string is returned. The function above also works for that case: len(text) - n is negative, so a different version could wrap, but with the n > 0 check and max(len(text) - n, 0) as the start it is safe: def lastchars(text, n): return text[max(len(text) - n, 0):] if n > 0 else ''.