NumPy Array Slicing
This lesson covers slicing NumPy arrays with the start:stop:step syntax in one dimension and extending it across rows and columns in two dimensions.
Slicing Basics: start:stop:step
Slicing lets you pull out a range of elements instead of one at a time, using the syntax arr[start:stop:step]. start is the first index included, stop is the index where the slice ends (excluded), and step controls how many elements are skipped between selections. Any of the three can be omitted: a missing start defaults to the beginning, a missing stop defaults to the end, and a missing step defaults to 1.
Slicing a 1-D Array
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70])
print(arr[1:5]) # [20 30 40 50]
print(arr[:4]) # [10 20 30 40]
print(arr[3:]) # [40 50 60 70]
print(arr[::2]) # [10 30 50 70]Negative Slicing and Reversal
Negative numbers work in slices the same way they do in indexing - they count from the end of the array. A negative step reverses the direction of the slice entirely, which is how arr[::-1] flips an array.
Slicing with Negative Numbers
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70])
print(arr[-3:]) # [50 60 70]
print(arr[:-2]) # [10 20 30 40 50]
print(arr[::-1]) # [70 60 50 40 30 20 10]Slicing 2-D Arrays
In a 2-D array, you slice each axis separately, separated by a comma: arr[row_slice, col_slice]. This lets you cut out a sub-block of rows and columns in a single expression.
Slicing a 2-D Array
import numpy as np
grid = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print(grid[0:2, 1:3])
# [[2 3]
# [6 7]]
print(grid[:, 2]) # every row, column 2 -> [ 3 7 11]
print(grid[1, :]) # row 1, every column -> [5 6 7 8]Exercise: NumPy Array Slicing
What does arr[1:5] return for a 1D array?