slice()
slice(stop) / slice(start, stop[, step]) Returns:
slice object · Updated March 13, 2026 · Built-in Functions built-in sequences slicing indexing
The slice() function creates a slice object that represents a set of indices for extracting portions of sequences like lists, strings, and tuples. Slice objects are useful when you want to reuse the same slicing operation multiple times or pass slicing parameters to functions.
Syntax
slice(stop)
slice(start, stop)
slice(start, stop, step)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
start | int | None | The starting index of the slice. None means beginning of the sequence. |
stop | int | — | The ending index (exclusive). This parameter is required. |
step | int | None | The step value. None means step of 1. Negative values reverse the direction. |
Examples
Basic usage
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a slice object
s = slice(5)
print(my_list[s])
# [0, 1, 2, 3, 4]
# Equivalent to my_list[:5]
With start and stop
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(1, 5)
print(my_list[s])
# [1, 2, 3, 4]
# Equivalent to my_list[1:5]
With step value
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(0, 10, 2)
print(my_list[s])
# [0, 2, 4, 6, 8]
# Equivalent to my_list[0:10:2]
Negative indices
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Last three elements
s = slice(-3, None)
print(my_list[s])
# [7, 8, 9]
# Reverse the list
s = slice(None, None, -1)
print(my_list[s])
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Common Patterns
Reusing slice objects
Create a slice once and use it multiple times:
header = slice(0, 3)
data = ["name", "age", "city", "Alice", "30", "NYC"]
print(data[header]) # ['name', 'age', 'city']
print(data[:3]) # Same result
Passing slices to functions
Slice objects work with any sequence type:
text = "hello world"
s = slice(0, 5)
print(text[s])
# hello
# Works with tuples too
tup = (1, 2, 3, 4, 5)
print(tup[s])
# (1, 2, 3, 4, 5)
Using .indices() method
The .indices() method maps a slice to a concrete range given a sequence length:
s = slice(1, 10, 2)
# For a sequence of length 7
start, stop, step = s.indices(7)
print(f"start={start}, stop={stop}, step={step}")
# start=1, stop=7, step=2
# This tells you which indices would be used
result = list(range(7))[s]
print(result)
# [1, 3, 5]
This is useful when you need to know the actual indices without having the sequence yet, or when working with functions that need to validate slice bounds.
Errors
IndexError with out-of-bounds stop
my_list = [1, 2, 3]
s = slice(0, 10)
try:
result = my_list[s]
print(result) # Still works - Python handles gracefully
except IndexError:
print("IndexError raised")
# [1, 2, 3] - No error, Python clamps to sequence length
Python is forgiving with slices and does not raise IndexError for out-of-bounds values. It simply clamps to the sequence bounds.