Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python slice() function

Reference for Python slice(): build reusable slice objects, start/stop/step defaults, indices(), and how slice() relates to the [start:stop:step] syntax.

The built-in slice() creates a slice object: a small value that stores a start, a stop and a step. It is what Python builds behind the scenes when you write items[1:4:2]. Creating one explicitly lets you name a slice, store it in a variable and reuse it on many sequences.

Slice objects are especially handy for fixed-width records, where field positions are defined once and applied to every line.

Python
middle = slice(1, 4)
[10, 20, 30, 40, 50][middle]   # [20, 30, 40]

Try it

Python Reusable slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python indices() and custom classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
slice(stop)
slice(start, stop)
slice(start, stop, step)
Name Description
start Index where the slice begins (included). Defaults to None, meaning the beginning (or the end when step is negative).
stop Index where it ends (excluded). Defaults to None, meaning the far end.
step Distance between items. Defaults to None, meaning 1. It cannot be 0.

Return value: a slice object with read-only attributes start, stop and step, plus the method indices(length).

Raises: TypeError for the wrong number of arguments; applying a slice with step 0 raises ValueError.

Usage notes

  • One argument means stop. slice(3) is slice(None, 3, None), the same as [:3].
  • None stands for "default". [::2] is slice(None, None, 2).
  • indices(length) returns a normalized (start, stop, step) tuple for a sequence of that length, with negatives resolved and bounds clamped, so you can pass it to range().
  • Out-of-range bounds are fine. Slicing never raises IndexError; it clamps and may return an empty sequence.
  • Slices copy. For lists, strings and tuples a slice builds a new object (shallow copy). NumPy arrays are the exception: they return views.
  • Slice assignment and deletion work on mutable sequences: nums[slice(2, 5)] = [...] can change the length; with an extended step the sizes must match.
  • Custom classes receive slice objects in __getitem__(). Multi-dimensional indexing passes a tuple, which may contain slices and ....
  • Slice objects are not hashable before Python 3.12; from 3.12 they are, so they can be dictionary keys.