Slice Function Python: How to Use It

When a Python task calls for selecting part of a sequence, you can describe the selection with slice(). Python’s slice() creates an object that stores bounds for use inside square brackets.

This article shows how to save a slice object and apply it to different sequences. It also explains how to represent an omitted bound with None.

TL;DR

Python’s slice() creates a reusable slice object that you can pass inside square brackets to select part of a sequence.

  • Use slice(stop) for items from the start up to stop, or slice(start, stop, step) for explicit bounds.
  • The stop boundary is excluded, and a step of zero raises ValueError.
  • Use None for an omitted bound when creating the object directly, such as slice(2, None).

What Is Python slice()?

Python’s built-in slice() constructs a slice object containing bounds for later use. Applying it inside square brackets selects items from a string, list, or tuple.

The stored values define a selection, not its result, so the object can be passed to another function or saved before the sequence is available.

Start is included and stop is excluded. For example, slice(1, 4) selects positions 1, 2, and 3. Negative bounds count back from the end, and a negative step walks backwards.

FormStored fieldsEffect when applied
slice(4)start=None, stop=4, step=NoneFrom the beginning up to index 4
slice(1, 4)start=1, stop=4, step=NonePositions 1, 2, and 3
slice(1, 5, 2)start=1, stop=5, step=2Positions 1 and 3

How I Reused a Slice Object Across Sequences

Create one slice object and apply it inside square brackets.

Step 1: Save the selection bounds

Pass start, stop, and step to slice() in that order. The list provides five labels so the selected positions are visible, and a second sequence shows that the object keeps its bounds rather than the first result.

items = ["red", "green", "blue", "gold", "white"]
selection = slice(1, 5, 2)
print(items[selection])
print(items[1:5:2])
print("abcdef"[selection])

try:
    items[slice(None, None, 0)]
except ValueError as error:
    print(type(error).__name__ + ": " + str(error))

text = "Python"
print(text[slice(-2, None)])
print(repr(text[slice(20, 30)]))

Run the saved file with python3 slice_probe.py. I ran that command and got the following output:

['green', 'gold']
['green', 'gold']
bd
ValueError: slice step cannot be zero
on
''
Terminal showing a reusable Python slice, equivalent notation, zero-step error, and boundary results

The paired list results agree, so the saved object and bracket expression select the same entries. The error line shows why step must move forward or backward. The final values come from the negative bound and the out-of-range bound, respectively.

Step 2: Apply the same object to another sequence

The saved bounds work on different sequences when their subscription supports slicing. In the output above, the list produced two color names, while the string “abcdef” produced bd from positions 1 and 3. This is useful when two records share a field layout even though their contents differ.

Step 3: Represent omitted bounds with None

A blank part of bracket notation becomes None in the constructor. For example, [2:] corresponds to slice(2, None), [:4] to slice(None, 4), and [::2] to slice(None, None, 2).

Use slice(None, None, -1) for reverse order. Leaving start and stop as None lets the sequence choose the ends for the negative direction, avoiding a guessed last index. For a partial reverse, choose a starting position to the right of the stop boundary because each move decreases the index.

Slice Bounds and Common Errors

A slice beginning beyond a string’s length returned an empty string in the probe. Direct indexing at a missing position instead raises IndexError.

CaseWhat happensWhat to change
step is 0ValueError: slice step cannot be zeroUse a positive or negative nonzero step.
start equals stopThe result is empty.Check whether both boundaries were meant to point to the same position.
negative step with forward boundsThe result is often empty because traversal moves away from stop.Use a start to the right of stop, or use None to reverse the whole sequence.

Conclusion

When selection rules need a name of their own, keep the slice object with the code that applies it. The Python documentation covers the constructor and its attributes, and the sequence reference describes how built-in types use slices.

Read the Python slice() documentation for the constructor and its attributes. For the surrounding sequence rules, see the common sequence operations reference, and AskPython’s guide to negative indexing in Python.

The related AskPython article on Python slicing syntax covers the broader bracket notation.

FAQ

These answers distinguish the slice constructor from the syntax used to retrieve items.

Is slice() a function or a statement in Python?

slice() is a built-in constructor that returns a slice object. Bracket notation such as items[1:4] is syntax that uses slice information to retrieve items.

What does slice(4) mean in Python?

It creates a slice object with start=None, stop=4, and step=None. Applied to a sequence, it selects from the beginning up to but excluding index 4.

How do you slice from an index to the end with slice()?

Use slice(start, None). For example, sequence[slice(2, None)] corresponds to sequence[2:].

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 189