Sub topic 3
Slicing arrays: start, stop, step, and negative indices
This chapter assumes you know basic Python list slicing and can create arrays with np.array, np.arange, and reshape. You should also know what an array's shape is. Here you will learn the full start:stop:step rules, how negative numbers change them, and how slices combine across several axes.
The slice syntax
A slice selects a regular run of positions along one axis. It has three parts, separated by colons.
array[start:stop:step]startis the first position included.stopis the position where selection ends. It is never included.stepis the distance between selected positions. It defaults to 1.
Any part can be left out. The same rules apply as for Python lists, with one important difference that the next chapter covers: a NumPy slice returns a view of the original data, not a copy.
import numpy as np
a = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
print(a[2:7]) # [2 3 4 5 6]
print(a[:3]) # [0 1 2]
print(a[7:]) # [7 8 9]
print(a[::3]) # [0 3 6 9]
print(a[1:8:3]) # [1 4 7]
print(a[:]) # [0 1 2 3 4 5 6 7 8 9]Because stop is excluded, a[i:j] has j - i elements when both bounds are in range. Adjacent slices such as a[:5] and a[5:] split an array with no overlap and no gap. That property is the main reason for the half-open convention.
Negative indices
A negative number counts from the end of the axis. For an axis of length n, the index -k means n - k. So -1 is the last element, -2 the one before it, and so on.
import numpy as np
a = np.arange(10)
print(a[-1]) # 9
print(a[-3:]) # [7 8 9] last three elements
print(a[:-3]) # [0 1 2 3 4 5 6] everything except the last three
print(a[-6:-2]) # [4 5 6 7]Negative values work for start and stop independently, and you can mix them with positive values. a[2:-2] drops the first two and last two elements. This is useful when you do not want to hard-code the length.
Negative steps
A negative step walks backward. This changes the meaning of the defaults.
- With a positive step, the default
startis the first element and the defaultstopis past the last one. - With a negative step, the default
startis the last element and the defaultstopis before the first one.
So a[::-1] reverses the array. When you give explicit bounds with a negative step, start must be the larger position and stop the smaller one, because you are moving toward lower positions.
import numpy as np
a = np.arange(10)
print(a[::-1]) # [9 8 7 6 5 4 3 2 1 0]
print(a[7:2:-2]) # [7 5 3]
print(a[-1:-6:-1]) # [9 8 7 6 5]
print(a[2:7:-1]) # [] wrong direction, so nothing is selectedThe last line is a frequent mistake. The slice is valid, but it selects nothing, because starting at 2 and moving backward never reaches 7.
Out-of-range bounds are clamped
An integer index outside the axis raises an IndexError. A slice never does. Its bounds are clamped to the valid range, and the result may be shorter or empty.
import numpy as np
a = np.arange(10)
print(a[2:100]) # [2 3 4 5 6 7 8 9]
print(a[-100:3]) # [0 1 2]
print(a[5:2]) # []
try:
a[100]
except IndexError as err:
print("IndexError:", err)This forgiving behavior is convenient for code such as a[:k] where k might exceed the length. It also hides bugs, because an off-by-one error or a wrong direction produces a short or empty array and no warning.
Seeing how Python resolves a slice
Python turns a[1:8:3] into a slice object. Its .indices(n) method shows the concrete (start, stop, step) triple for an axis of length n, after negative values are converted and bounds are clamped. This is a good debugging tool.
import numpy as np
s = slice(-3, None)
print(s.indices(10)) # (7, 10, 1)
print(slice(2, 100).indices(10)) # (2, 10, 1)
print(slice(None, None, -1).indices(10)) # (9, -1, -1)
# Number of elements a slice selects on an axis of length 10
start, stop, step = slice(1, 8, 3).indices(10)
print(len(range(start, stop, step))) # 3
a = np.arange(10)
print(a[slice(1, 8, 3)]) # [1 4 7]
print(np.s_[1:8:3]) # slice(1, 8, 3)Note the third result. For a reversed full slice, the resolved stop is -1. That -1 means "before position 0", not "the last element", because .indices has already finished converting negatives. You can store slice objects in variables and reuse them across several arrays. np.s_ is a helper that builds a slice object from the familiar bracket syntax.
Slicing several axes
For an array with more than one axis, separate the per-axis slices with commas. Each slice applies to its own axis, in order. Axes you do not mention are taken in full.
import numpy as np
m = np.arange(20).reshape(4, 5)
# [[ 0 1 2 3 4]
# [ 5 6 7 8 9]
# [10 11 12 13 14]
# [15 16 17 18 19]]
print(m[1:3, 1:4]) # [[ 6 7 8]
# [11 12 13]]
print(m[::2, ::2]) # [[ 0 2 4]
# [10 12 14]]
print(m[-2:, -2:]) # [[13 14]
# [18 19]]
print(m[::-1, 0]) # [15 10 5 0]
print(m[1:3]) # rows 1 and 2, all columnsThe last line shows the omitted-axis rule. m[1:3] is the same as m[1:3, :]. Each axis has its own start, stop, and step, so you can reverse one axis and subsample another in the same expression, as in m[::-1, ::2].
Integers versus slices: the shape rule
Mixing an integer and a slice looks harmless, but it changes the result's number of dimensions.
- An integer index removes that axis from the result.
- A slice keeps the axis, even if it selects only one position.
import numpy as np
m = np.arange(20).reshape(4, 5)
print(m[1].shape) # (5,) row as a 1-D array
print(m[1:2].shape) # (1, 5) row kept as a 2-D array
print(m[:, 2].shape) # (4,) column as a 1-D array
print(m[:, 2:3].shape) # (4, 1) column kept as a 2-D arrayThe choice matters when you later combine the result with other arrays. A (4,) array and a (4, 1) array behave very differently under broadcasting. If you need a column vector, use m[:, 2:3] instead of m[:, 2]. The next chapters show np.newaxis as another way to restore an axis.
Assigning through a slice
A slice on the left side of = writes into the original array. The right side must have a shape that matches the selected region or can be broadcast to it.
import numpy as np
b = np.arange(10)
b[::2] = 0
print(b) # [0 1 0 3 0 5 0 7 0 9]
b[1::2] = [10, 30, 50, 70, 90]
print(b) # [ 0 10 0 30 0 50 0 70 0 90]
grid = np.zeros((3, 4), dtype=int)
grid[1:, 1:3] = 7
grid[0] = [1, 2, 3, 4]
print(grid)
# [[1 2 3 4]
# [0 7 7 0]
# [0 7 7 0]]A scalar is broadcast to every selected position. A sequence must supply exactly as many values as there are selected positions along each axis, or be broadcastable to that shape. Otherwise NumPy raises a ValueError. For example, b[:3] = [1, 2] fails because two values cannot fill three positions.
Assignment also converts values to the array's dtype. Assigning 2.9 into an integer array stores 2, because the value is truncated rather than rounded.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `IndexError: index 10 is out of bounds` | An integer index past the end of an axis | Check the shape, or use a slice if clamping is acceptable |
| Empty result, no error | Start and stop point opposite to the step direction | Swap the bounds, or use a negative step |
| `TypeError: slice indices must be integers` | A float such as `n / 2` used as a bound | Use `n // 2` or `int(...)` |
| `ValueError: slice step cannot be zero` | `a[::0]` or a step variable equal to 0 | Guard the step value |
| `ValueError` on assignment | Right side has an incompatible shape | Compare `target.shape` with `values.shape` |
| `IndexError: too many indices` | More comma-separated entries than axes | Compare the number of entries with `a.ndim` |
Edge cases to remember
a[-0:]is not "the last zero elements". Since-0equals0, it means the whole array.- To take the last
kelements,a[-k:]fails whenkis 0 because it returns the whole array. Usea[len(a) - k:]whenkcan be zero. - Excluding the last
kelements has the same problem.a[:-k]returns an empty array whenkis 0. Usea[:len(a) - k]instead. - A reversed slice is a view with a negative stride. It costs nothing to create, but some later operations may need a contiguous copy.
- The
stopbound with a negative step can't be written as-1to mean "include index 0". Leavestopempty, as ina[5::-1].
import numpy as np
a = np.arange(10)
print(a[5::-1]) # [5 4 3 2 1 0] includes position 0
print(a[5:-1:-1]) # [] -1 here means position 9, not "before 0"
k = 0
print(a[-k:]) # whole array, usually not what you want
print(a[len(a) - k:]) # [] as intendedSummary
- A slice is
start:stop:step. The stop is excluded, and each part is optional. - Negative start and stop count from the end. A negative step reverses direction and flips the defaults.
- Out-of-range slice bounds are clamped and give short or empty results, while out-of-range integers raise
IndexError. - Multi-axis slices apply one slice per axis, and missing trailing axes are taken in full.
- Integers drop an axis and slices keep it.
- Slice assignment writes into the original array and requires matching or broadcastable shapes.
Exercise
Given a = np.arange(10) and m = np.arange(20).reshape(4, 5), what do a[8:2:-3] and m[1:, ::-2] return, and what is the shape of m[1:, ::-2]?
Show answer
a[8:2:-3] starts at 8 and steps back by 3, stopping before 2, so it returns [8 5]. m[1:, ::-2] takes rows 1 to 3 and, in each row, columns 4, 2, 0, giving [[ 9 7 5], [14 12 10], [19 17 15]] laid out as three rows of three values: [[9 7 5] [14 12 10] [19 17 15]]... more exactly, rows [9, 7, 5], [14, 12, 10], [19, 17, 15]. Its shape is (3, 3).
Exercise
You need the last k elements of a 1-D array a, and k can be 0. Why does a[-k:] fail for that case, and what expression is correct?
Show answer
-0 equals 0, so a[-0:] is a[0:], which returns the whole array instead of an empty one. Use a[len(a) - k:], which gives an empty array when k is 0.
Exercise
Starting from m = np.arange(20).reshape(4, 5), write one expression that returns the third column as an array of shape (4, 1), and one that sets every second element of the last row to -1.
Show answer
m[:, 2:3] keeps the column axis, so its shape is (4, 1). m[-1, ::2] = -1 writes -1 into columns 0, 2, and 4 of the last row, giving [-1 16 -1 18 -1].