Indexing and Slicing Arrays
After creating an array, you’ll often need to access individual elements or extract specific sections.
This process is called indexing and slicing.
Indexing
Indexing retrieves individual items based on their position.
Like Python lists, NumPy arrays use zero-based indexing — the first element is at position 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 allows you to select a range of elements using the : operator.
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.