For a multi-dimensional array, you provide one slice, or index, per dimension, separated by commas, e.g. selecting rows 1-2 and every other column at once. Using a bare colon for a dimension selects everything along it, and omitting trailing dimensions entirely selects all of them implicitly. Crucially, basic slicing always returns a view sharing the same underlying memory as the original array, so modifying a slice's elements modifies the original array's data too — this is a deliberate performance optimization, but a frequent source of surprising bugs.
1Understanding Basic Slicing
For a multi-dimensional array, you provide one slice, or index, per dimension, separated by commas, e.g. selecting rows 1-2 and every other column at once. Using a bare colon for a dimension selects everything along it, and omitting trailing dimensions entirely selects all of them implicitly. Crucially, basic slicing always returns a view sharing the same underlying memory as the original array, so modifying a slice's elements modifies the original array's data too — this is a deliberate performance optimization, but a frequent source of surprising bugs.
Basic slicing, using colons and integers, returns a view, but fancy indexing, using a list or array of indices, always returns a copy — the two look similar but behave very differently regarding whether you're modifying the original data.
import numpy as np
matrix = np.arange(16).reshape(4, 4)
print(matrix[1:3, 1:3])2Practical Example
Here is a real-world application of Basic Slicing showing how it is used in production NumPy code.
import numpy as np
arr = np.arange(10)
slice_view = arr[2:5]
slice_view[0] = 99
print(arr)3Best Practices
Follow these guidelines when working with Basic Slicing:
1. Call .copy() explicitly on a slice's result when you need an independent array and don't want changes to propagate back to the original
2. Use a bare colon to select an entire dimension explicitly, for readability, rather than relying on omitting trailing dimensions
3. Remember basic slicing views share memory with the original array — be deliberate about whether that shared-mutation behavior is what you actually want
Tip: Basic slicing, using colons and integers, returns a view, but fancy indexing, using a list or array of indices, always returns a copy — the two look similar but behave very differently regarding whether you're modifying the original data.
import numpy as np
matrix = np.arange(16).reshape(4, 4)
print(matrix[1:3, 1:3])