Python has an inbuilt slice() function that can be used to create a slice object, which can be used in various other operations such as indexing and unpacking. The slice() function takes three arguments: start, stop, and step.
slice(start, stop, step)
The start argument is the index at which the slice begins. If no value is provided for start, it defaults to 0. The stop argument is the index at which the slice ends. If no value is provided for stop, it defaults to the end of the sequence. The step argument is the number of indices between items in the slice. If no value is provided for step, it defaults to 1.
For example, if you want to create a slice object that extracts every second number starting from the third, you could use the following code:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2, len(nums), 2)
print(nums[s])
This would output [2, 4, 6, 8]
You can also use the slice object in other ways, such as with the built-in function list()
and str()
to create new list and string respectively.
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2, len(nums), 2)
print(list(nums)[s])
This would also output [2, 4, 6, 8]