Python 3 reference · Built-in Functions

Python slice() Function

Create a slice object, the thing behind a[start:stop:step]. Useful to name and reuse a slice.

Python 3 Since 3.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

slice(stop)
slice(start, stop, step=None)

Parameters

ParameterDescription
start optional Start index. Default: None
stop Stop index (not included).
step optional Step between items. Default: None

Return value

A slice object.

Examples

Reusable slicesTry it yourself
letters = "abcdefgh"
first_three = slice(3)
every_other = slice(None, None, 2)
print(letters[first_three], letters[every_other])

Output

abc aceg
Name the fields of fixed-width textTry it yourself
record = "2026-10-21 ERROR disk full"
DATE, LEVEL, MESSAGE = slice(0, 10), slice(11, 16), slice(17, None)
print(record[DATE], "|", record[LEVEL], "|", record[MESSAGE])

Output

2026-10-21 | ERROR | disk full

Good to know

Slice objects are hashable since Python 3.12, so they can be dictionary keys.

Version history

VersionChange
Python 3.0Added
Python 3.12Slice objects became hashable.

In other languages

Was this page helpful?