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
Syntax
slice(stop)
slice(start, stop, step=None)
Parameters
| Parameter | Description |
|---|---|
start optional |
Start index. Default: None |
stop |
Stop index (not included). |
step optional |
Step between items. Default: None |
Return value
A slice object.
Examples
letters = "abcdefgh"
first_three = slice(3)
every_other = slice(None, None, 2)
print(letters[first_three], letters[every_other])
Output
abc aceg
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.12 | Slice objects became hashable. |
Related
range()· Create an immutable sequence of integers from start up to (but not including) stop, in steps. Used in for loops.list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.- Python Strings · tutorial
- Python Lists · tutorial