Slicing takes a range of elements from an array with the syntax [start:stop:step]. The start index is included, the stop index is not.
Slice a 1-D array
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
print(arr[4:])
print(arr[:4])
Output
[2 3 4 5]
[5 6 7]
[1 2 3 4]
Leave out
startto begin at index 0Leave out
stopto go to the endThe stop index itself is never included
Negative slicing
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
Output
[5 6]
Use a step
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
print(arr[::2])
print(arr[::-1])
Output
[2 4]
[1 3 5 7]
[7 6 5 4 3 2 1]
A step of -1 walks backwards, which reverses the array.
Slice a 2-D array
Slice rows and columns separately, with a comma between them:
Example
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
print(arr[1, 1:4]) # row 1, columns 1 to 3
print(arr[0:2, 2]) # rows 0 and 1, column 2
print(arr[0:2, 1:4]) # rows 0-1, columns 1-3
Output
[7 8 9]
[3 8]
[[2 3 4]
[7 8 9]]
A slice does not copy data — it is a view of the original array, so changing the slice changes the original too. The next lesson explains why.