Thuta Learning
IntermediateData & Databasesintermediate

Array Slicing

Relax. We'll talk through this in plain words — no textbook voice.

Slicing means cutting out a chunk of an array. The syntax is start:stop:step, and the stop index isn't included. Slicing is extremely handy when you need to pick out certain rows/columns from a big chunk of data.

python
import numpy as np

numbers = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Index 2 to 5:", numbers[2:6])
print("Every 2 steps:", numbers[::2])

matrix = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
])

print("
First 2 rows, columns 1 to 2:
", matrix[:2, 1:3])

numbers[2:6] grabs index 2 through 5. 6 isn't included. numbers[::2] grabs from start to end with a step of 2. For 2-D slicing, whatever comes before the comma refers to rows, and after the comma refers to columns.

You should see
Index 2 to 5: [2 3 4 5] Every 2 steps: [0 2 4 6 8] First 2 rows, columns 1 to 2: [[2 3] [6 7]]

Info

A slice result can be a view into the original array, so in some cases modifying the slice will affect the original array too. If you want a fully independent copy, use .copy().

Easy traps

  • If you write a start or stop beyond the list's length, you won't get an error — it'll just return as much as it can. That can sometimes hide a bug, so check the shape/result.

Exercise

You'll use slicing almost every day for things like grabbing the first 100 rows of a CSV table as test data, or splitting off the last column as labels.

You'll know it worked when:

Array Slicing | Thuta Learning