NumPy Array Slicing

Lesson 6 of 17

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

Python
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

Plain Text
[2 3 4 5]
[5 6 7]
[1 2 3 4]
  • Leave out start to begin at index 0

  • Leave out stop to go to the end

  • The stop index itself is never included

Negative slicing

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])

Output

Plain Text
[5 6]

Use a step

Example

Python
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

Plain Text
[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

Python
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

Plain Text
[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.