Indexing and Slicing Arrays
After creating an array, you often need to access specific elements or select parts of it.
This is done with indexing and slicing.
Indexing
Indexing retrieves one item using its position.
Like Python lists, NumPy arrays start at index 0
.
Indexing a 1D Array
arr = np.array([10, 20, 30, 40])
print(arr[1]) # Output: 20
For 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 selects 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 in 2D arrays.
Slicing a 2D Array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix[:, 1]) # Output: [2 5]
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.