Module 2 · Lesson 1

Basic Indexing & Slicing

Array indexing extends Python’s list[start:stop:step] syntax to any number of dimensions, with one index/slice per axis, separated by commas: arr[row_slice, col_slice]. Negative indices count from the end, and a negative step reverses direction.

ExpressionMeaning
arr[2]element/row at index 2
arr[-1]last element/row
arr[1:4]indices 1, 2, 3
arr[::2]every other element
arr[::-1]reversed
arr[1:3, 0:2]rows 1-2, columns 0-1
arr = np.arange(10)
print(arr[2], arr[-1], arr[1:4], arr[::2], arr[::-1])

grid = np.arange(16).reshape(4, 4)
print(grid)
print(grid[1:3, 0:2])   # rows 1-2, cols 0-1
print(grid[:, 2])       # every row, column 2
print(grid[-1, :])      # last row

Output:

2 9 [1 2 3] [0 2 4 6 8] [9 8 7 6 5 4 3 2 1 0]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
[[4 5]
 [8 9]]
[ 2  6 10 14]
[12 13 14 15]
1.1

Border of a grid

Write border(grid) that takes a 2-D array and returns its last row reversed — i.e. grid[-1][::-1].

💡 Hint

Index the last row with grid[-1], then reverse it with [::-1].

✅ Solution
def border(grid):
    return grid[-1][::-1]
1.2

Every other row and column

Write downsample(grid) that returns every other row AND every other column of a 2-D array, starting from index 0 (i.e. grid[0::2, 0::2]).

💡 Hint

Apply a step-2 slice to both axes at once: grid[0::2, 0::2].

✅ Solution
def downsample(grid):
    return grid[0::2, 0::2]