a[start:stop]
items start through stop-1a[start:]
items start through the rest of the arraya[:stop]
items from the beginning through stop-1a[:]
a copy of the whole arraya[-1]
last item in the arraya[-2:]
last two items in the arraya[:-2]
everything except the last two itemsa[::-1]
all items in the array, reverseda[1::-1]
the first two items, reverseda[-3::-1]
everything except the last two items, reverseda[:-3:-1]
the last two items, reverseda[::2]
extracts elements of list at even positionsa[1::2]
extracts elements of list at odd positionsa[::3]
similar to abovea[1::3]
similar to above
If we adopt the notation [start:stop:step]
, start
is always inclusive, stop
is always exclusive.
1 |
|
One can substitute None for any of the empty spaces. For example [None:None] makes a whole copy. This is useful when you need to specify the end of the range using a variable and need to include the last item.
Slicing builtin types returns a copy but that’s not universal. Notably, [slicing NumPy arrays] (https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) returns a view that shares memory with the original.