Last updated

Array Slicing

Definition: Slicing extracts a range of elements using [start:stop:step]. The start is included, the stop is excluded.

Example 1 — 1D slicing

import numpy as np
a = np.array([0, 1, 2, 3, 4, 5])
print(a[1:4])   # [1 2 3]
print(a[:3])    # [0 1 2]
print(a[3:])    # [3 4 5]
print(a[::2])   # [0 2 4]  (every 2nd)

Example 2 — slicing rows and columns

import numpy as np
b = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
print(b[0, :])    # whole first row -> [1 2 3]
print(b[:, 1])    # whole second column -> [2 5 8]
print(b[0:2, 1:]) # top-right block

The colon : on its own means "everything along this axis".

💡 Tip: b[:, 0] grabs a column — a pattern you will use constantly with data tables.

Try it Yourself
Output

          
Ad · responsive