slice() Slice object
Last updated: 2026-09-22
slice() Slice object
slice(stop) or slice(start, stop[, step]) returns a slice object used for __getitem__.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
slice(stop)
slice(start, stop[, step])
⚙️ Parameters
| stop Required | The stop index (exclusive); in the one-arg form it is the slice endpoint. |
|---|---|
| start Optional | The start index (inclusive); None when omitted.(Default:None) |
| step Optional | The step; None when omitted.(Default:None) |
Returns:A slice object with start/stop/step attributes, passable to __getitem__.
💥 Raises
TypeError— Raised when an argument is not an integer (no __index__).
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
[1, 3]
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QIs slice(1, 5, 2) the same as lst[1:5:2]?
AYes — lst[1:5:2] internally calls lst[slice(1, 5, 2)]; a slice object suits dynamically constructed slices (e.g. when the slice parameters come from config or user input).
QMust the start/stop/step of a slice object always be integers?
ANo, they can be omitted as None: the start and step of slice(5) are both None, meaning 'from the start up to index 5', consistent with lst[:5].
QHow does a custom class support slicing?
AImplement __getitem__(self, key); when key is a slice object, parse its start/stop/step and apply the corresponding logic.
QMust slice arguments be integers?
AYes — passing a non-integer (e.g. slice('a', 'b')) raises a TypeError; the arguments must implement __index__.