Sub topic 5
Indexing and slicing
This chapter assumes you can create arrays and read their shape and ndim. It also assumes you know Python list indexing and slice syntax (start:stop:step). It covers the basic indexing forms that return views or single elements. Boolean masks and integer-array (fancy) indexing have their own chapter.
Indexing with integers
A single integer picks one position along the first axis. For a 1-D array that gives a scalar. Negative integers count from the end, as in lists.
import numpy as np
x = np.arange(10)
print(x[0]) # 0
print(x[-1]) # 9For arrays with more than one axis, give one index per axis, separated by commas. NumPy reads the comma-separated indices as a single tuple.
import numpy as np
a = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a[1, 2]) # 6
print(a[-1, -1]) # 11
print(a[1][2]) # 6, same value but slowera[1][2] works, but it first builds the intermediate array a[1] and then indexes that. a[1, 2] does the lookup in one step. Prefer the comma form.
If you give fewer indices than the array has axes, the missing ones default to : (everything along that axis).
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[0]) # [0 1 2 3]
print(a[0].shape) # (4,)An out-of-range integer raises IndexError:
import numpy as np
x = np.arange(5)
try:
x[10]
except IndexError as e:
print(e) # index 10 is out of bounds for axis 0 with size 5Slicing
A slice start:stop:step selects a range along one axis. The rules match Python lists:
startis included andstopis excluded.- Omitted values default to the start, the end, and a step of 1.
- A negative step walks backwards.
import numpy as np
x = np.arange(10)
print(x[2:6]) # [2 3 4 5]
print(x[::3]) # [0 3 6 9]
print(x[-3:]) # [7 8 9]
print(x[::-1]) # [9 8 7 6 5 4 3 2 1 0]
print(x[7:2:-2]) # [7 5 3]Slices never raise an error for out-of-range bounds. They clamp to the array edges, so x[3:100] on a five-element array returns the elements from position 3 to the end, and an empty range gives an empty array.
import numpy as np
x = np.arange(5)
print(x[3:100]) # [3 4]
print(x[7:9]) # []In a multi-dimensional array, put one slice per axis. This lets you cut out sub-blocks, rows, and columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 1]) # [1 5 9], column 1
print(a[1:, ::2]) # [[ 4 6]
# [ 8 10]]
print(a[::-1]) # rows in reverse orderHow indices change the shape
The most common source of confusion is the shape of the result. Each kind of index treats its axis differently:
| Index on an axis | Effect on the result |
|---|---|
| Integer, such as `2` | The axis is removed |
| Slice, such as `1:3` or `:` | The axis is kept (its length may shrink) |
| `np.newaxis` (or `None`) | A new axis of length 1 is inserted |
| `...` (Ellipsis) | Expands to as many `:` as needed |
So an integer lowers ndim by one, and a slice does not. A slice of length one still keeps the axis:
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 1].shape) # (3,) integer removes the axis
print(a[:, 1:2].shape) # (3, 1) slice keeps the axisThis difference matters for broadcasting and matrix code. A shape (3,) array and a shape (3, 1) array behave very differently when combined with other arrays, as a later chapter shows. Use a[:, 1:2] when you need a column that is still two-dimensional.
Ellipsis and newaxis
... stands for "all the remaining axes". It is useful when you care about the first or last axis of an array with many dimensions, or when the number of dimensions can vary.
import numpy as np
c = np.arange(24).reshape(2, 3, 4)
print(c[..., 0].shape) # (2, 3), same as c[:, :, 0]
print(c[1, :, 2]) # [14 18 22]
print(c[0, ..., 1:3].shape) # (3, 2)You can use only one ... in a single index.
np.newaxis is an alias for None. It adds a length-1 axis at that position, which is the usual way to turn a 1-D array into a row or a column:
import numpy as np
v = np.array([1, 2, 3])
print(v.shape) # (3,)
print(v[np.newaxis, :].shape) # (1, 3), a row
print(v[:, np.newaxis].shape) # (3, 1), a columnAssigning through indices and slices
Anything you can use to read, you can use on the left side of = to write. The right side can be a scalar or an array. A scalar is broadcast across the selected region. An array must have a shape that broadcasts to the shape of the selection.
import numpy as np
b = np.zeros((3, 4), dtype=int)
b[1:, ::2] = 7
print(b)
# [[0 0 0 0]
# [7 0 7 0]
# [7 0 7 0]]
b[:, 1] = [1, 2, 3]
print(b)
# [[0 1 0 0]
# [7 2 7 0]
# [7 3 7 0]]The array keeps its own dtype. Assigned values are cast to it, so floats written into an integer array are truncated without a warning:
import numpy as np
b = np.zeros(3, dtype=int)
b[0] = 3.9
print(b) # [3 0 0]Assigning to a slice writes into the original array's memory, because a basic slice is a view. The next chapter covers views and copies in detail.
Common errors and gotchas
- Wrong index count. Giving more indices than the array has axes raises
IndexError: too many indices for array. Checka.ndimfirst. - Shape mismatch on assignment.
b[:, 1] = [1, 2]fails when the column has 3 elements, with aValueErrorabout broadcasting. The right side must match the selected shape or broadcast to it. - Expecting a slice to stay 2-D after an integer.
a[:, 1]is 1-D. Usea[:, 1:2]ora[:, [1]]to keep two dimensions. - Slices silently clamp. A typo such as
x[0:50]on a short array gives no error. Integer indices are strict, but slices are forgiving.
Exercise
Let c = np.arange(24).reshape(2, 3, 4). What are the shapes of c[1], c[:, 0, :], c[..., 1:3], and c[:, :, np.newaxis, 0]?
Show answer
c[1] has shape (3, 4), because the integer removes axis 0 and the missing indices default to :. c[:, 0, :] has shape (2, 4), because the integer removes axis 1. c[..., 1:3] has shape (2, 3, 2), because the slice keeps the last axis but shortens it to length 2. c[:, :, np.newaxis, 0] has shape (2, 3, 1): the two leading slices keep axes of length 2 and 3, np.newaxis inserts a length-1 axis, and the trailing integer removes the original last axis.
Exercise
Given a = np.arange(12).reshape(3, 4), write one assignment that sets the last two columns of the last two rows to 0, then say how many elements change.
Show answer
a[1:, 2:] = 0. The slice 1: selects rows 1 and 2, and 2: selects columns 2 and 3, so 2 x 2 = 4 elements change (the values 6, 7, 10, and 11).