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.