Sub topic 3
Slicing arrays: start, stop, step, and negative indices
This chapter assumes you know Python list slicing, can create arrays with np.arange and reshape, and know what an array's shape is. A slice selects a range of positions along an axis. It uses the same start:stop:step rules as Python lists, applied to each axis of an array.
The three parts of a slice
A slice start:stop:step has these rules:
startis the first position included. It defaults to the beginning.stopis the first position excluded. It defaults to the end.stepis the distance between selected positions. It defaults to 1.
Any part can be omitted. The stop position is never included, so x[2:5] returns three elements: positions 2, 3, and 4.
import numpy as np
x = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
print(x[2:8:2]) # [2 4 6]
print(x[:3]) # [0 1 2]
print(x[7:]) # [7 8 9]
print(x[::3]) # [0 3 6 9]Negative indices and negative steps
A negative index counts from the end. Position -1 is the last element, -2 is the one before it, and so on. This works in both start and stop.
A negative step walks backward. In that case the defaults swap: start defaults to the last element, and stop defaults to "before the first element". So x[::-1] reverses the array.
import numpy as np
x = np.arange(10)
print(x[-3:]) # [7 8 9]
print(x[:-1]) # [0 1 2 3 4 5 6 7 8]
print(x[::-1]) # [9 8 7 6 5 4 3 2 1 0]
print(x[7:2:-2]) # [7 5 3]
print(x[-1:-4:-1]) # [9 8 7]With a negative step, start must be larger than stop, or you get an empty result. x[2:7:-1] is empty because walking backward from 2 never reaches 7.
Slices never raise out-of-range errors
A single integer index outside the array raises IndexError. A slice does not. It clips to the array's bounds and returns whatever overlaps, which may be nothing.
import numpy as np
x = np.arange(10)
print(x[5:100]) # [5 6 7 8 9]
print(x[20:]) # []
print(x[5:2]) # []
# x[10] would raise IndexErrorThis is convenient, but it can hide off-by-one mistakes. An empty result with no error is a signal to check your bounds.
Slicing in several dimensions
For a 2-D array, separate the slices for each axis with commas. The first slice applies to axis 0 (rows) and the second to axis 1 (columns). Any axis you leave out is taken in full.
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[0:2, 1:3]) # [[1 2]
# [5 6]]
print(a[:, -1]) # [ 3 7 11]
print(a[::2, ::-1]) # [[ 3 2 1 0]
# [11 10 9 8]]In the last line, ::2 takes rows 0 and 2, and ::-1 reverses the columns of each selected row.
Integers drop an axis, slices keep it
Mixing an integer with a slice changes the result's number of dimensions. An integer index removes that axis. A slice keeps it, even when it selects only one position.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[1, :].shape) # (4,)
print(a[1:2, :].shape) # (1, 4)
print(a[:, 1].shape) # (3,)
print(a[:, 1:2].shape) # (3, 1)This matters when you later combine the result with other arrays. A column of shape (3,) and a column of shape (3, 1) behave differently in arithmetic and broadcasting. Use 1:2 instead of 1 when you need to keep the axis.
Quick reference
| Expression | Meaning |
|---|---|
| `x[a:b]` | Positions `a` up to but not including `b` |
| `x[a:]` | From `a` to the end |
| `x[:b]` | From the start up to but not including `b` |
| `x[::k]` | Every `k`-th element |
| `x[-n:]` | The last `n` elements |
| `x[::-1]` | The array reversed |
Common mistakes
- Expecting
stopto be included.x[0:3]has three elements, not four. - Reading an empty result as a bug in NumPy. Out-of-range slices clip silently.
- Using a negative step with
startsmaller thanstop. - Forgetting that an integer index removes an axis, which then changes the result's shape.
Exercise
Given a = np.arange(12).reshape(3, 4), what are the values and the shape of a[1:, ::2]?
Show answer
Rows 1 and 2 are selected by 1:, and columns 0 and 2 by ::2. The result is [[4 6], [8 10]] with shape (2, 2).
Exercise
Given x = np.arange(10), write one slice that returns [8 6 4 2].
Show answer
x[8:1:-2]. It starts at 8, steps back by 2, and stops before reaching 1. x[-2:0:-2] gives the same result.