Indexing and Slicing Arrays
After creating an array, we often want to access specific elements or select parts of it.
This is where indexing and slicing come in.
Indexing
Indexing lets you access one item using its position.
Like Python lists, NumPy arrays start at index 0
.
arr = np.array([10, 20, 30, 40])
print(arr[1]) # Output: 20
In 2D arrays, use two indices: arr[row, column]
.
Indexing a 2D Array
matrix = np.array([[1, 2], [3, 4]])
print(matrix[1, 0]) # Output: 3
Slicing
Slicing lets you grab a range of values using :
notation.
Slicing a 1D Array
arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4]) # Output: [20 30 40]
You can also slice rows or columns from 2D arrays.
Slicing a 2D Array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix[:, 1]) # Output: [2 5] (second column)
Summary
- Use square brackets
[]
for indexing and slicing - 1D:
arr[start:stop]
- 2D:
arr[row, col]
or use:
to slice rows/columns
What’s Next
You’ll now practice accessing and slicing values from arrays in a Jupyter Notebook.