all Python 3Built-in typesterm
slice
slices
The built-in slice object type: slice(start, stop, step), created by a[start:stop:step].
Syntax
slice(start, stop, step)
You rarely build a slice by hand: it pays off when the same slice is reused under a name in several places, or when you write your own __getitem__ and need to tell an integer index from a slice object. As with range, a single argument is stop, not start: slice(5) means start=None, stop=5. To resolve it against a concrete length use indices(): s.indices(len(seq)) returns a ready triple with None and negative values already sorted out.
Examples
s = slice(1, 5, 2)
print((s.start, s.stop, s.step)) # → (1, 5, 2)
print('abcdefgh'[s]) # → bd
print([0, 1, 2, 3, 4][slice(2, 4)]) # → [2, 3]
print('abcdef'[slice(None, None, -1)]) # → fedcba
print(slice(5).indices(3)) # → (0, 3, 1)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy