In Python, the slice() function is used to create a slice object, which can be used for slicing operations on sequences.
Function Syntax
slice([start,] stop[, step])
start: Optional, the starting position of the slice (inclusive), defaults to0.stop: Required, the ending position of the slice (exclusive).step: Optional, the step size, defaults to1.
The slice() function returns a slice object, which can be passed to the slice operator [] of a sequence (such as a string, list, or tuple).
Examples of the slice() Function
Creating simple slice objects:
s1 = slice(3)
s2 = slice(2, 5)
s3 = slice(3, 8, 2)
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Equivalent to data[0:3]
print(data[s1]) # [0, 1, 2]
# Equivalent to data[2:5]
print(data[s2]) # [2, 3, 4]
# Equivalent to data[3:8:2]
print(data[s3]) # [3, 5, 7]
Common attributes of a slice object:
s = slice(2, 10, 3)
# Start position
print(s.start) # 2
# Stop position
print(s.stop) # 10
# Step size
print(s.step) # 3
# Get actual indices
print(s.indices(5)) # (2, 5, 3)
print(s.indices(15)) # (2, 10, 3)
The indices() method converts a slice object into a (start, stop, step) tuple that can be used on a sequence of a given length, automatically handling boundaries and negative indices.
Enabling custom types to support slicing operations:
class MySequence:
def __init__(self,data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, key):
if isinstance(key, slice):
print(f"Processing slice: {key}")
# Use the indices method to convert into a tuple usable on a sequence of a given length
start, stop, step = key.indices(len(self))
result = []
for i in range(start,stop,step):
result.append(self.data[i])
return result
if isinstance(key, int):
return self.data[key]
else:
raise TypeError("Index must be an integer or slice")
seq = MySequence(list(range(10)))
s1 = slice(5)
s2 = slice(2,5)
s3 = slice(2,5,3)
print(seq[s1])
print(seq[s2])
print(seq[s3])
print(seq[5])
print(seq[5:8])
Program Output
Processing slice: slice(None, 5, None) [0, 1, 2, 3, 4] Processing slice: slice(2, 5, None) [2, 3, 4] Processing slice: slice(2, 5, 3) [2] 5 Processing slice: slice(5, 8, None) [5, 6, 7]