slice()
The thing that `x[i:j:k]` builds. Rarely constructed directly, but essential when writing __getitem__ or extended indexing.
Demo
slice() builds a slice object — the same thing that `x[i:j:k]` syntax creates. The demo shows the slice object AND how it would apply to a demo list. Any argument can be omitted (None) — for "from the start" use start=None; for "to the end" use stop=None. Negative indices count from the end of the sequence. Negative step counts down.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| start | int | None | no (None) | The first index (inclusive). None means "from the beginning". In the one-arg form (`slice(stop)`), start defaults to None. |
| stop | int | None | yes | The upper bound (exclusive). None means "to the end". The only argument in the one-arg form. |
| step | int | None | no (None) | The stride. None means 1. Negative values step backward. |
Return value
slice — A slice object with .start, .stop, .step attributes. Any of the three can be None. Slice objects are what `x[i:j:k]` syntax creates behind the scenes and passes to __getitem__.
Common patterns
s = slice(start, stop, step) result = data[s]
class Vec: def __getitem__(self, key): if isinstance(key, slice): return self._range(key.start, key.stop, key.step)
s = slice(-3, None) s.indices(10) # (7, 10, 1)
HEADER = slice(0, 8) BODY = slice(8, None) header, body = data[HEADER], data[BODY]
Examples
Pitfalls
slice(5)
slice(5, None)
slice(0, 5, 1)
slice(None, 5, None)
type(slice(5))
isinstance(slice(5), slice)
for i in slice(5): ...
for i in range(*slice(0, 5).indices(len(x))): ...
When to use
- Custom __getitem__ that supports extended indexing
- Reusable named slices for readable code
- Slicing when the endpoints are computed at runtime
- Interfacing with numpy / pandas / other libraries that consume slice objects
- Literal slice → just write x[i:j:k]
- Iteration → use range() instead
- Storage of index ranges as a tuple — a slice object is dedicated for the job
Notes
FAQ
When the start/stop/step values are variables you compute at runtime, or when you want to store a slice as a named constant. In everyday code you just write x[i:j:k] — Python calls slice() for you.