The slice()
function creates a slice object used to extract parts of sequences (lists, tuples, strings, etc.). It’s useful for data manipulation, working with large datasets, and creating custom slicing behavior.
Example
numbers = [0, 1, 2, 3, 4, 5]
s = slice(1, 4) # Create a slice object
print(numbers[s])
Output:
[1, 2, 3]
Extracts elements from index 1
to 3
.
Syntax
slice(start, stop, step)
- start (optional) → Index to start slicing (
default: 0
). - stop → Index to stop at (not included).
- step (optional) → Step size (
default: 1
).
1. Using slice()
on a List
data = ["a", "b", "c", "d", "e"]
s = slice(1, 4)
print(data[s])
# Output: ['b', 'c', 'd']
Equivalent to data[1:4]
.
2. Using slice()
with Step
nums = [0, 1, 2, 3, 4, 5, 6]
s = slice(0, 7, 2)
print(nums[s])
# Output: [0, 2, 4, 6]
Extracts every second element.
3. Using slice()
on Strings
text = "Python"
s = slice(1, 4)
print(text[s])
# Output: 'yth'
Works just like list slicing.
4. Slicing a Tuple
values = (10, 20, 30, 40, 50)
s = slice(2, 4)
print(values[s])
# Output: (30, 40)
Returns a new tuple.
5. Using slice()
with Negative Indexing
nums = [10, 20, 30, 40, 50]
s = slice(-4, -1)
print(nums[s])
# Output: [20, 30, 40]
Works with negative indexes too.
6. Using slice()
with range()
s = slice(2, 10, 3)
print(list(range(15))[s])
# Output: [2, 5, 8]
Works with range()
objects too.
7. Using slice()
Dynamically
start, stop, step = 1, 5, 2
s = slice(start, stop, step)
data = ["A", "B", "C", "D", "E", "F"]
print(data[s])
# Output: ['B', 'D']
Stores slice parameters dynamically.
8. Extracting slice()
Values
s = slice(1, 5, 2)
print(s.start, s.stop, s.step)
# Output: 1 5 2
Useful for working with slicing programmatically.
Key Notes
- ✔ Works with lists, tuples, strings, and ranges.
- ✔ Supports start, stop, and step parameters.
- ✔ Can be used dynamically for flexible slicing.
- ✔ Equivalent to
obj[start:stop:step]
but more versatile.
By using slice()
, you can efficiently extract data, manipulate sequences, and work with slicing dynamically. 🚀