Sub topic 12
Slice objects and slice.indices()
This chapter assumes you can already write slices such as s[1:4], s[::-1] and s[-3:], and that you understand the defaults for omitted bounds. You should also be comfortable with try/except. Here you will see what Python does with the part between the square brackets, and how to use that machinery yourself.
A slice expression builds an object
When you write s[1:5:2], Python does not pass three separate numbers to the string. It builds one slice object from them and hands it to the __getitem__ method of s. A small class that returns whatever key it receives shows this:
class Show:
def __getitem__(self, key):
return key
probe = Show()
print(probe[1:5:2])
print(probe[::-1])
print(probe[3:])
print(probe[1:2, 3])The output is:
slice(1, 5, 2)
slice(None, None, -1)
slice(3, None, None)
(slice(1, 2, None), 3)Two details matter here. First, every bound you leave out becomes None. The slice object stores no defaults. Second, a comma makes the key a tuple, which is how libraries such as NumPy receive multi-dimensional slices. Strings accept only a single integer or a single slice.
Creating slice objects directly
The slice constructor mirrors the three positions of the bracket syntax:
| Call | Equivalent bracket syntax |
|---|---|
| `slice(stop)` | `s[:stop]` |
| `slice(start, stop)` | `s[start:stop]` |
| `slice(start, stop, step)` | `s[start:stop:step]` |
| `slice(None, None, -1)` | `s[::-1]` |
Note the one-argument form. slice(3) means stop at 3, not start at 3. To write s[3:] as an object, use slice(3, None).
A slice object has three read-only attributes, start, stop and step. It stores exactly what you gave it:
s = "Python"
last_three = slice(-3, None)
print(last_three.start, last_three.stop, last_three.step)
print(s[last_three])
print("Pandas"[last_three])This prints -3 None None, then hon, then das. The object does not know which string it will be applied to. The same object works on any sequence, and the negative start is resolved only when it is used.
Why name a slice
The main practical use is giving meaning to positions that would otherwise be magic numbers. Fixed-width text is the classic case:
line = "2026-11-26 ERROR disk full"
DATE = slice(0, 10)
LEVEL = slice(11, 16)
MESSAGE = slice(17, None)
print(line[DATE])
print(line[LEVEL])
print(line[MESSAGE])The output is 2026-11-26, ERROR and disk full. If the layout changes, you edit three definitions instead of hunting through every line[11:16] in the program. Slice objects also work well as dictionary values, for example {"date": slice(0, 10), ...}, so you can loop over field names.
Asking what a slice means: indices()
Because a slice object holds raw, unresolved values, you sometimes need to know which positions it would select for a particular length. slice.indices(length) answers this. It returns a tuple (start, stop, step) of concrete integers after applying the omitted-bound defaults, the negative-index rules, and clamping.
s = "Python"
last_three = slice(-3, None)
print(s[last_three])
print(last_three.indices(len(s)))
print(slice(None, None, -1).indices(len(s)))This prints hon, (3, 6, 1) and (5, -1, -1). The first tuple says that slice(-3, None) on a length-6 string means start at 3, stop at 6, step 1. The second says that a full reverse starts at index 5 and walks down with step -1 until it reaches -1.
The tuple is built to be passed straight to range, which gives you the exact positions:
print(list(range(*slice(-3, None).indices(6))))
print(list(range(*slice(None, None, -1).indices(6))))The results are [3, 4, 5] and [5, 4, 3, 2, 1, 0].
What indices() normalizes
Three kinds of adjustment happen inside indices():
- A
Nonebound is replaced by the default for the direction. With a positive step, the start is 0 and the stop is the length. With a negative step, the start islength - 1and the stop is -1. - A negative start or stop has
lengthadded to it. - A result that is still out of range is clamped. This is the same behavior that stops slices from raising
IndexError.
Here is the clamping on a length-6 string:
for sl in (slice(2, 100), slice(10, None), slice(-100, 3), slice(3, 1)):
start, stop, step = sl.indices(6)
print(sl, (start, stop, step), list(range(start, stop, step)))The output is:
slice(2, 100, None) (2, 6, 1) [2, 3, 4, 5]
slice(10, None, None) (6, 6, 1) []
slice(-100, 3, None) (0, 3, 1) [0, 1, 2]
slice(3, 1, None) (3, 1, 1) []Notice that slice(3, 1) is not rewritten to something sensible. It stays (3, 1, 1), and the empty result comes from range(3, 1, 1) having nothing to produce. The same happens in a real slice, where s[3:1] gives an empty string.
With a negative step, the clamp limits are different. A start that is too large clamps to length - 1, and a stop that is too small clamps to -1. For example, slice(10, None, -1).indices(6) returns (5, -1, -1).
Gotcha: the -1 in the result is not an index
The tuple from indices() is meant for range, not for feeding back into a slice. In (5, -1, -1), the -1 stop means "go past index 0". If you put it back into bracket syntax, Python applies the negative-index rule and reads it as the last character:
s = "Python"
start, stop, step = slice(None, None, -1).indices(len(s))
print(repr(s[start:stop:step]))
print("".join(s[i] for i in range(start, stop, step)))The first line prints '' because s[5:-1:-1] means start at 5 and stop at 5. The second line prints nohtyP. When you need positions, loop over range(*indices). Do not rebuild a slice from the tuple.
Using indices() in your own classes
If you write a class that supports obj[a:b:c], indices() saves you from re-implementing the bound rules. Your __getitem__ receives either an integer or a slice:
class Text:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, key):
if isinstance(key, slice):
start, stop, step = key.indices(len(self.data))
return "".join(self.data[i] for i in range(start, stop, step))
return self.data[key]
t = Text("Python")
print(t[1:4])
print(t[::-1])
print(t[-2])
print(repr(t[10:]))The output is yth, nohtyP, o and ''. Out-of-range slices behave like those on a built-in string, and the single-index path still raises IndexError for bad positions because it delegates to the real string.
Errors you can trigger
slice objects validate their pieces only when they are used:
attempts = (
lambda: slice(0, 3, 0).indices(6),
lambda: "Python"[slice(1.5)],
lambda: slice(None).indices(-1),
)
for attempt in attempts:
try:
attempt()
except (ValueError, TypeError) as e:
print(type(e).__name__)This prints ValueError, TypeError and ValueError. A step of zero is rejected, a float bound is rejected when the slice is applied (creating slice(1.5) itself succeeds), and a negative length is rejected by indices(). Bounds must be integers, None, or objects that define __index__.
Code points, not visible characters
Slicing and indices() count code points, which are the units that len() counts. A visible character built from several code points can be cut apart:
s = "cafe\u0301"
print(len(s))
print(s[:4])
print(slice(None, 4).indices(len(s)))Here len(s) is 5, s[:4] is cafe without the accent, and the tuple is (0, 4, 1). A slice object cannot know about display characters. If your slices must respect them, you need a library that segments text into grapheme clusters, because the slice machinery will not.
Exercise
What does slice(-2, None).indices(5) return, and which characters does it select from "hello"?
Show answer
It returns (3, 5, 1). The negative start -2 becomes 5 + (-2) = 3, the omitted stop becomes the length 5, and the omitted step is 1. It selects positions 3 and 4, which give "lo".
Exercise
Using only indices() and range, list the positions selected by slice(None, None, -2) on a string of length 7, and explain why the stop in the tuple is -1.
Show answer
slice(None, None, -2).indices(7) returns (6, -1, -2), and list(range(6, -1, -2)) is [6, 4, 2, 0]. With a negative step the default stop is -1, a value just before index 0, so that range includes position 0 and then stops. It is a range endpoint, not an index.