Indexing and slicing

Intermediate

Introduction

Once data is in an array, you constantly need parts of it: one value, a row, a column, a block, every other sample. NumPy extends Python's indexing and slicing to every dimension at once, so that a[:, 1] is "column 1" and a[0:2, 1:3] is a 2 by 2 block, with no loops. The rules are few, and they are the base for everything later in the course.

How it works

Indices count from 0, and negative indices count from the end. In a 2-D array you give one index per axis, separated by a comma:

a = np.arange(1, 13).reshape(3, 4)
print(a)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
print(a[1, 2])      # 7
print(a[-1, -1])    # 12

a[1][2] also works, as with lists, but it builds the row first and then indexes it; a[1, 2] is one direct lookup and the usual NumPy style.

A slice start:stop:step selects positions from start up to but not including stop. Any part may be left out: : alone means the whole axis, ::2 every other position, ::-1 the axis reversed. Slices work on each axis independently:

print(a[0])          # [1 2 3 4]      row 0
print(a[:, 1])       # [ 2  6 10]     column 1
print(a[0:2, 1:3])
# [[2 3]
#  [6 7]]

Mixing integers and slices decides the shape of the result. An integer index removes its axis: a[0] and a[:, 1] are 1-D. A slice keeps its axis, even when it selects one position: a[0:1, :] has shape (1, 4), still 2-D. Knowing this avoids most shape surprises when you later combine arrays.

An index beyond the end is an error, with a message naming the axis and its size: a[3, 0] raises IndexError: index 3 is out of bounds for axis 0 with size 3. Slices never raise this error: a slice past the end just stops at the end.

Example

# A model of NumPy indexing on a 3 x 4 grid, built from Python lists.
grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

def index(a, i, j):  # a[i, j]
    return a[i][j]

def slice2d(a, rows, cols):  # a[rows, cols] with two slices
    return [row[cols] for row in a[rows]]

print("a[1, 2] =", index(grid, 1, 2))
print("a[-1, -1] =", index(grid, -1, -1))
print("a[0] =", grid[0])
print("a[:, 1] =", [row[1] for row in grid])
print("a[0:2, 1:3] =", slice2d(grid, slice(0, 2), slice(1, 3)))
print("a[::2, ::3] =", slice2d(grid, slice(None, None, 2), slice(None, None, 3)))
Open in compiler

Line by line

  1. grid models the 3 by 4 array as a list of rows.
  2. index is a[i, j]: row i, then column j, with negative indices from the end.
  3. A column is the same position taken from every row.
  4. slice2d applies one slice to the rows and another to each row, as a[rows, cols] does in one step.

Expected result

a[1, 2] = 7
a[-1, -1] = 12
a[0] = [1, 2, 3, 4]
a[:, 1] = [2, 6, 10]
a[0:2, 1:3] = [[2, 3], [6, 7]]
a[::2, ::3] = [[1, 4], [9, 12]]

In the real world

Images are indexed as img[row, column, channel], so img[:, :, 0] is the red channel and img[100:200, 50:150] a crop. Time series use x[::10] to keep every tenth sample, and tables of measurements use data[:, 2] to take one column.

Common mistakes

  • Expecting stop to be included: a[0:2] is two rows, not three.
  • Losing a dimension by accident: a[:, 1] is 1-D; write a[:, 1:2] to keep a column 2-D.
  • Using a[i][j] in loops over large arrays, which is slower than a[i, j].
  • Indexing past the end after a shape change.

Best practices

  • Use a[i, j] with commas for multi-dimensional access.
  • Print .shape of a slice when you are unsure whether it kept its dimensions.
  • Prefer slices over loops to take rows, columns and blocks.

Summary

Indexing takes one index or slice per axis, separated by commas, with negative indices counting from the end. Slices start:stop:step exclude the stop and never fail at the edges, integer indices drop their axis while slices keep it, and an index out of range raises an IndexError that names the axis and its size.

Quick check

1. For a of shape (3, 4), what is the shape of a[:, 1]?
2. What does a[0:2] select from a 2-D array?
3. What is the shape of a[0:1, :] for a of shape (3, 4)?
4. What happens with a[5] when a has 3 rows?

Key takeaways

  • a[i, j] takes one index per axis; negative indices count from the end.
  • Slices work on every axis: a[0:2, 1:3] is a block of rows and columns.
  • An integer index removes its axis from the result; a slice keeps it.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.