class slice(stop)
class slice(start, stop [, step])
The slice class returns an object representing the indices specified by range(start, stop, step).
- start: First index to generate in the sequence.
- stop: Limit value of the index to be generated.
- step: (Optional) value to add to each index to generate the next one.
The result is an object of class slice.
We can create a slice object that includes references to indexes 1, 3 and 5 (that is, indexes starting at 2, ending at 6 and with a jump of 2) with the following code:
index = slice(1, 6, 2)
index
slice(1, 6, 2)
Now if we have, for example, a list:
a = list("ABCDEFGH")
a
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
...we can extract the elements referenced by our indexes in the following way:
a[index]
['B', 'D', 'F']