Indexing Slicing and Iterating

Once you have a NumPy array, indexing lets you access individual elements, slicing lets you extract sub-sections, and iteration lets you loop through its contents - three essential skills for working with real data.

Indexing

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[0])    # 10
print(arr[-1])   # 50 (last element)

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix[1, 2])   # 6 (row 1, column 2)

Slicing

Slicing uses the start:stop:step syntax to extract a range of elements without needing a loop.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])     # [20 30 40]
print(arr[:3])      # [10 20 30]
print(arr[::2])     # [10 30 50] - every second element

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix[:2, 1:])   # rows 0-1, columns 1 onward

Iterating Over Arrays

import numpy as np

arr = np.array([1, 2, 3])
for x in arr:
    print(x)

matrix = np.array([[1, 2], [3, 4]])
for row in matrix:
    print(row)

for value in np.nditer(matrix):   # iterate over every individual element
    print(value)
A NumPy slice returns a "view" of the original array, not a copy - modifying a sliced sub-array will also change the original array unless you explicitly use .copy() to create an independent copy.

Coming Up Next

Next, you'll learn about NumPy array attributes - properties that tell you an array's shape, size, and data type.

Selecting Data With Conditions

Real analysis rarely asks for "element three". It asks for "all scores above the pass mark". NumPy handles this with boolean masks: a comparison produces an array of True and False values, and that array can be used as an index.

import numpy as np

scores = np.array([45, 78, 92, 33, 67, 88])
passed = scores >= 50
print(passed)          # [False  True  True False  True  True]
print(scores[passed])  # [78 92 67 88]

# Combine conditions with & (and) or | (or); parentheses are required
print(scores[(scores > 60) & (scores < 90)])  # [78 67 88]

# Assign through a mask
scores[scores < 50] = 50
print(scores)          # [50 78 92 50 67 88]

# Label every value at once
labels = np.where(scores >= 60, "pass", "review")
print(labels)          # ['review' 'pass' 'pass' 'review' 'pass' 'pass']

Use & and | rather than the Python words and and or, which raise an error with arrays. The parentheses matter too, because & binds more tightly than comparison operators.

Masks are the foundation of data cleaning. The same idea lets you drop outliers, replace missing markers such as -1 with a sensible value, or count how many rows meet a rule with passed.sum(), since each True counts as one. Libraries like pandas use exactly this pattern for filtering rows, so learning it here pays off later.

Fancy Indexing, Columns and Reversing

Passing a list of positions picks exactly those elements. Unlike a slice, this always returns a copy, so changing the result leaves the original alone.

arr = np.array([10, 20, 30, 40, 50])
picked = arr[[0, 2, 4]]
picked[0] = 999
print(picked)      # [999  30  50]
print(arr[0])      # 10 - original unchanged

m = np.arange(1, 10).reshape(3, 3)
print(m[:, 0])     # [1 4 7]  first column as a 1-D array, shape (3,)
print(m[:, 0:1])   # first column kept as 2-D, shape (3, 1)
print(m[::-1])     # rows in reverse order
print(m[[0, 2]])   # rows 0 and 2 only

A slice with a negative step, such as [::-1], walks backwards and is still a view, so it costs almost nothing even on large arrays. The difference between m[:, 0] and m[:, 0:1] matters when you feed data into libraries that expect a 2-D input, such as many machine learning models.

Looping With Positions, and When Not to Loop

When you need both the position and the value, np.ndenumerate returns an index tuple with each element:

for (i, j), value in np.ndenumerate(m):
    if value % 4 == 0:
        print(f"row {i}, col {j}: {value}")
# row 1, col 0: 4
# row 2, col 1: 8

Even so, explicit loops should be your last option. NumPy runs whole-array operations in compiled code, which is usually far faster than a Python loop over the same data.

prices = np.array([120.0, 80.0, 45.5])
qty = np.array([2, 5, 10])

total = (prices * qty).sum()   # vectorised, no loop
print(total)                    # 1095.0

A good habit is to ask: "Can I express this as a mask, a slice or an arithmetic operation on the whole array?" Most of the time the answer is yes.

Common Errors to Watch For

  • IndexError: asking for a position beyond the array's size; check arr.shape first.
  • Unexpected changes: editing a slice and forgetting it is a view of the original data.
  • Expecting a view from a mask: boolean and fancy indexing return copies, so editing the result does not update the source unless you assign back through the index.
  • Confusing m[1][2] with m[1, 2]: both work for reading, but the comma form is clearer and faster, and it behaves correctly with slices.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course