Reuse indexing rules
Apply identical bounds to multiple sequences or repeatedly access one sequence without duplicating slicing expressions.
Python · Function
slice creates a reusable object describing a range of indices. Sequences can consume it for indexed access, and Python also creates such objects from slicing syntax.
slice constructs an object that describes a range of indices in the same way as range(start, stop, step). The object stores start, stop, and step; sequence types can interpret it for indexed access, and slicing syntax creates equivalent objects internally.
slice(start, stop, step=None, /)| Name | Type | Description |
|---|---|---|
start | object | Beginning index; defaults to None. |
stop | object | Ending index or required range endpoint. |
step | object | Stride between indices; defaults to None. |
A slice object representing the indices described by the arguments.
start or step when constructing the object gives it the value None; the receiving sequence determines how those bounds are interpreted.a[start:stop:step] notation creates slice semantics automatically, so explicitly calling slice is mainly useful when storing or reusing the bounds.values = [0, 1, 2, 3, 4, 5]
window = slice(1, 5, 2)
print(values[window])
print(window.start, window.stop, window.step)A slice object can be reused for indexed access and exposes the three arguments it stores.
Apply identical bounds to multiple sequences or repeatedly access one sequence without duplicating slicing expressions.
Pass start, stop, and step as data to code that performs indexing later.
Inspect or validate bounds through the object’s read-only attributes before applying them.
slice do?slice creates a slice object representing indices specified by range(start, stop, step). It does not itself return the selected elements; a sequence uses the object during subscription.
Follow-up: How can the object’s bounds be inspected? Read its start, stop, and step attributes; these are read-only and contain the supplied values or defaults.
The signature is slice(start, stop, step=None). start and step default to None, while stop is the required endpoint in the documented constructor form.
Follow-up: What syntax creates an equivalent object without calling slice? Extended slicing such as a[start:stop:step] generates a slice object internally.
A slice object stores three read-only data attributes: start, stop, and step. They expose the argument values, including None when an argument used its default.
Follow-up: Does the object select data by itself? No; it describes indices, and the indexed object or an extension interprets that description.
rangeobject.__getitem____index__