{:check ["true"]}
import numpy as np
x = np.arange(10)
x
x[5]
x[5:8]
x[5:8] = 12
x
Memory model
Slice of an array is a view. Modifications to the slice will modify the underlying array.
x_slice = x[5:8]
x_slice
x_slice[-1] = -100
x_slice
x
y = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
y
There are two dimensions, so we need two indices to get a single entry in the matrix.
y[0][2]
y[0, 2]
We can get an entire row:
y[0]
y[0,:]
We can get an entire column.
y[:, 2]
The general syntax of slicing along a dimension.
i:j
: from $i$ to $j-1$ inclusive.:j
: from $0$ to $j-1$ inclusive.i:
: from $i$ to the last index in the dimension.i:j:k
: from $i$ to $j-1$ inclusive, and skip with step size $k$: $i$, $i+k$, $i+2k$, $\dots$y[0:2, 2]
y[0:, 2]
y[:2, 2]
y[:2, :2]
y[:,[2,1,0]]
y[:,2::-1]
y[1:2, :2]
Note:
Observe y[1:2, :2]
is not the same as y[1,:2]
.
y[1:2, :2]
is (1,2). This is two dimensional.y[1,:2]
is (2,). This is one dimensional.