The Power of NumPy

7. NumPy Slicing

Slicing

NumPy Arrays are also capable of slicing, like Python lists.

Slices are formatted with brackets (like how you access elements in an array normally).

It is important to keep in mind the zero-indexing.

Slicing works like [start : end] or [start : end : step] (similar to np.arange()).

If you just pass one number [ : end], start defaults to 0.

Passing one number like this [start : ] defaults end to the end of the array.

Not passing step defaults to 1.

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

print(arr[1:5])
# prints [2 3 4 5]

print(arr[1:5:2])
# prints [2 4]

print(arr[:4])
# prints [1 2 3 4]

print(arr[2:])
# prints [3 4 5 6 7 8 9]

Slicing also works for multi-dimensional arrays.

Try it out yourself!