Creating arrays is only useful if you can get values back out. In Part 2 we built arrays of every shape; in this third part of our NumPy Fundamentals series we learn to select from them. Some of it will feel familiar from Python lists, and some of it, especially filtering with conditions, is where NumPy starts to feel genuinely powerful.
We cover single elements, slices, rows and columns of a 2D array, the important difference between a view and a copy, boolean masks, and picking values by a list of positions.
Indexing and slicing a 1D array
A one-dimensional array works just like a list. Indexes start at 0, negative indexes count from the end, and slices use start:stop:step:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0], a[-1], a[1:4], a[::2])
10 50 [20 30 40] [10 30 50]
If slicing feels rusty, it is exactly the same syntax we used on strings and lists in the Python series: the stop position is excluded, and leaving a part out means "from the start" or "to the end".
Rows and columns of a 2D array
For a 2D array you give one index per dimension, separated by a comma: rows first, then columns.
m = np.arange(1, 13).reshape(3, 4)
print(m)
print(m[1, 2]) # row 1, column 2
print(m[0]) # the whole first row
print(m[:, 1]) # every row, column 1
print(m[1:, 2:]) # bottom-right block
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
7
[1 2 3 4]
[ 2 6 10]
[[ 7 8]
[11 12]]
The : on its own means "everything along this dimension", so m[:, 1] reads as "all rows, column 1". Write m[1, 2] rather than m[1][2]: both work, but the first does one lookup and is the NumPy style. (reshape turns the 12 numbers into a 3×4 table; we cover it properly in Part 5.)
Views vs copies: the trap everyone hits once
Here is the most important difference from lists. Slicing a list gives you a new list. Slicing a NumPy array gives you a view: a window onto the same data in memory. Change the view and you change the original:
view = a[1:4]
view[0] = 999
print(a)
[ 10 999 30 40 50]
NumPy does this deliberately. Copying a slice of a large array would waste time and memory, so it shares the data instead. When you genuinely want an independent array, ask for a copy:
b = np.array([10, 20, 30, 40, 50])
copy = b[1:4].copy()
copy[0] = 999
print(b)
[10 20 30 40 50]
The original is untouched. A good habit: if you slice an array and then modify the slice, decide on purpose whether you want .copy().
Boolean masks: filtering with a condition
This is where NumPy shines. Comparing an array with a value gives an array of True/False, one per element, called a mask:
scores = np.array([45, 82, 67, 91, 38, 74])
print(scores > 60)
print(scores[scores > 60])
[False True True True False True]
[82 67 91 74]
Putting the mask inside the square brackets keeps only the elements where it is True. Compare that with writing a for loop with an if and appending to a new list: the NumPy version is one expression and runs in compiled code.
To combine conditions, use & (and), | (or) and ~ (not), and put each condition in brackets:
print(scores[(scores >= 60) & (scores < 90)])
[82 67 74]
The brackets matter: without them Python's operator precedence evaluates 60 & scores first and you get an error or a wrong answer. Also note you cannot use the words and and or here; those work on single values, not arrays.
Masks also work on the left of an assignment, which makes "fix every value that matches" a one-liner. Here every score below 40 is raised to 40:
scores[scores < 40] = 40
print(scores)
[45 82 67 91 40 74]
Fancy indexing and np.where
You can also pass a list of positions to pick several elements at once. This is called fancy indexing, and unlike slicing it always returns a copy:
print(a[[0, 2, 4]])
[10 30 50]
Finally, np.where chooses between two values element by element, like an if/else applied to the whole array:
print(np.where(scores >= 60, "pass", "fail"))
['fail' 'pass' 'pass' 'pass' 'fail' 'pass']

Clipping values, and indexing in 3D
A very common clean-up job is forcing values into a range: percentages between 0 and 100, sensor readings within physical limits, pixel values between 0 and 255. You could do it with two boolean masks, but np.clip does both ends in one call:
v = np.array([-5, 3, 12, 7, 25])
print(np.clip(v, 0, 10))
[ 0 3 10 7 10]
Everything below 0 becomes 0 and everything above 10 becomes 10; values in range are untouched.
Indexing works the same way in any number of dimensions: one index or slice per axis, separated by commas. A 3D array of shape (2, 3, 4) can be read as 2 "pages", each a 3×4 table:
cube = np.arange(24).reshape(2, 3, 4)
print(cube[1, 2, 3], cube[:, 0, 0], cube[0].shape)
23 [ 0 12] (3, 4)
cube[1, 2, 3] is page 1, row 2, column 3: the last value, 23. cube[:, 0, 0] takes the first value of every page, and cube[0] is the whole first page, a 3×4 table. This is exactly how you work with images, where the three axes are row, column and colour channel: img[:, :, 0] is the red channel of every pixel, and img[100:200, 50:150] crops a region. Once 2D slicing makes sense, 3D is just one more comma.
Practice exercises
Start from m = np.arange(1, 17).reshape(4, 4), a 4×4 table of the numbers 1 to 16.
- Get the four corner values as a 2×2 array.
- Get every even number in the table.
- Get the diagonal (top-left to bottom-right).
- Copy row 1, set the copy to zeros, and confirm
mis unchanged.
m = np.arange(1, 17).reshape(4, 4)
print(m[[0, -1]][:, [0, -1]])
print(m[m % 2 == 0])
print(np.diag(m))
row = m[1].copy(); row[:] = 0; print(m[1])
[[ 1 4]
[13 16]]
[ 2 4 6 8 10 12 14 16]
[ 1 6 11 16]
[5 6 7 8]
The first answer selects the first and last rows, then the first and last columns of those. Without .copy() in the last exercise, row 1 of m would have become zeros.
Common mistakes
- Changing a slice and being surprised the original changed. Slices are views; use
.copy()when you need independence. - Using
and/orwith arrays. Use&,|and~, and wrap each condition in brackets. - Writing
m[1][2]everywhere. It works but is slower and becomes confusing with slices. Preferm[1, 2]andm[:, 2]. - Expecting a mask to keep the shape.
m[m > 5]on a 2D array returns a flat 1D array of the matching values.
Wrapping up
You can now pull out single values, rows, columns and blocks, filter with conditions, update matching elements in place and choose between values with np.where. Above all, remember that slices are views. Next, in Vectorised Maths and Broadcasting, we calculate with whole arrays at once and learn the broadcasting rules that let arrays of different shapes work together.
Comments (0)
No comments yet — be the first to share your thoughts.