All About Python Slicing
Explanation
The core of slicing in Python is using colons : inside square brackets [].
data[start : stop : step]
start: the starting position to slice the data (inclusive)stop: the ending position to slice the data (exclusive)step: the stride (step size) for slicing
In other words, spelled out, data[start : stop : step] means slicing data from the element at index start up to index stop - 1, taking every step-th element.
First, the part after the second colon (the step) can be omitted; in that case it is equivalent to :1.
data[start : stop] == data[start : stop : 1]
Also, start, stop, and step can each be omitted, so all of the examples below are valid. The defaults are start=0, stop=len(data), step=1.
data[start : stop : ]
data[start : : step]
data[ : stop : step]
data[start : :]
data[: stop :]
data[: : step]
data[::]
data[:]
Negative step
You can provide a negative step. When step is negative, if you explicitly specify start and stop, you must give start a value greater than stop. Using data[::-1] returns all elements in reverse order.
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[7:3:-1]
[7, 6, 5, 4]
>>> a[7:1:-2]
[7, 5, 3]
Negative indices
slice()
If a particular slice range is used repeatedly, you can create it as a variable using slice().
Notes
Be aware that slicing beyond the maximum index does not raise an error; Python will simply slice up to the available range.
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[0:100]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[3:100]
[3, 4, 5, 6, 7, 8, 9]
