Indexing means picking out one value from an array, and slicing means picking out a range of values. They are the operations you'll use most in NumPy: getting the first five rows of a dataset, one column of a table, or the pixels in one corner of an image.
If you know Python list indexing, 1D arrays will feel familiar. 2D arrays add one new idea, a comma between the row and column, and this lesson walks through it step by step with pictures in table form.
Indexing a 1D array
Positions start at 0. Negative numbers count from the end, so -1 is the last value:
import numpy as np
temps = np.array([31, 33, 35, 34, 30, 29, 32])
print(temps[0]) # 31 (first)
print(temps[3]) # 34 (fourth)
print(temps[-1]) # 32 (last)
print(temps[-2]) # 29 (second to last)
Asking for a position that doesn't exist, such as temps[7], raises IndexError: index 7 is out of bounds for axis 0 with size 7.
Slicing a 1D array
A slice is written start:stop:step. The stop position isn't included, exactly like Python lists:
print(temps[1:4]) # [33 35 34] positions 1, 2, 3
print(temps[:3]) # [31 33 35] from the start
print(temps[4:]) # [30 29 32] to the end
print(temps[::2]) # [31 35 30 32] every second value
print(temps[::-1]) # [32 29 30 34 35 33 31] reversed
Leaving out start means "from the beginning", and leaving out stop means "to the end". A handy way to remember the stop rule: temps[:3] gives you exactly 3 values.
You can also assign to a slice to change many values at once:
temps[:2] = 0
print(temps) # [ 0 0 35 34 30 29 32]
Indexing a 2D array
A 2D array is a table with rows and columns. Write the row number, a comma, then the column number:
scores = np.array([
[72, 85, 91], # student 0
[64, 70, 88], # student 1
[90, 95, 79], # student 2
[55, 60, 75], # student 3
])
# maths science english
print(scores[1, 2]) # 88 row 1, column 2
print(scores[-1, 0]) # 55 last row, first column
You may also see scores[1][2]. It gives the same answer but is slower, because it first builds the whole row and then indexes it. Use the comma form.
Slicing rows and columns
Put a slice on either side of the comma. A colon on its own means "everything along this axis":
print(scores[0]) # [72 85 91] row 0
print(scores[:, 0]) # [72 64 90 55] column 0: every row, column 0
print(scores[:2, 1:]) # rows 0-1, columns 1-2
[72 85 91]
[72 64 90 55]
[[85 91]
[70 88]]
Read scores[:, 0] aloud as "all rows, column 0". That's how you get one feature from a dataset where rows are examples and columns are features, which is how scikit-learn expects data.
| Code | Meaning | Result shape |
|---|---|---|
scores[1, 2] | One value | a single number |
scores[1] or scores[1, :] | One row | (3,) |
scores[:, 1] | One column | (4,) |
scores[:2, :2] | Top-left block | (2, 2) |
scores[::2] | Every second row | (2, 3) |
Keeping the dimension
Notice that scores[:, 0] returns a 1D array of 4 values, not a column. Sometimes you need it to stay 2D, for example because scikit-learn wants a table of features. Use a slice of length one instead of a single number:
print(scores[:, 0].shape) # (4,)
print(scores[:, 0:1].shape) # (4, 1)
Fancy indexing: picking a list of positions
Pass a list of positions to pick values that aren't next to each other, in any order you like:
print(scores[[0, 2]]) # rows 0 and 2
print(scores[:, [2, 0]]) # english, then maths
[[72 85 91]
[90 95 79]]
[[91 72]
[88 64]
[79 90]
[75 55]]
This is called fancy indexing. It's useful for shuffling data, choosing specific samples, or reordering columns.
Slices are views, not copies
This is the one thing that surprises people coming from Python lists. A NumPy slice doesn't copy the data; it's a view into the same memory. Change the slice and you change the original:
first_row = scores[0]
first_row[0] = 100
print(scores[0]) # [100 85 91] the original changed too
When you want an independent copy, say so with .copy():
backup = scores[0].copy()
Fancy indexing always returns a copy. The full story is in NumPy copy vs view.
Practice
Use this array for the questions:
a = np.arange(1, 13).reshape(3, 4)
print(a)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
- Get the value 7, the last column, and the middle row.
Show the answer
print(a[1, 2]) # 7
print(a[:, -1]) # [ 4 8 12]
print(a[1]) # [5 6 7 8]
- Get the 2 × 2 block
[[6, 7], [10, 11]].
Show the answer
print(a[1:, 1:3])
Rows 1 to the end, columns 1 and 2 (stop 3 isn't included).
- Reverse the order of the rows, and separately pick columns 0 and 3 only.
Show the answer
print(a[::-1])
print(a[:, [0, 3]])
Interview questions
What is the difference between a[1][2] and a[1, 2]?
They return the same value, but a[1][2] indexes twice: it creates the row a[1] first, then takes item 2. a[1, 2] is a single, faster lookup, and only the comma form works with slices on both axes, like a[:, 2].
Does slicing a NumPy array create a copy?
No. Basic slicing returns a view that shares memory with the original, so changes to one show in the other. Fancy indexing (with a list or array of positions) and boolean indexing return copies. Use .copy() to get an independent array from a slice.
How do you select the last column of a 2D array?
a[:, -1]: all rows, last column. Use a[:, -1:] to keep it as a 2D column of shape (n, 1).
What to learn next
- Pick values by condition with boolean indexing and np.where.
- Change an array's shape with reshape, flatten and transpose.