Slicing lets you extract portions (subarrays) from an existing array by specifying a range of indices.
The syntax is similar to Python lists: arr[start:stop]
where start
is inclusive, and stop
is exclusive.
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
print(arr[1:4]) # Output: [20 30 40]
If start
is omitted, it defaults to 0; if stop
is omitted, it defaults to the end of the array.
print(arr[:3]) # Output: [10 20 30] (from start to index 2)
print(arr[3:]) # Output: [40 50 60] (from index 3 to end)
Negative indices work from the end of the array.
print(arr[-4:-1]) # Output: [30 40 50]
You can add a third parameter to specify the step or the interval between elements:
print(arr[0:6:2]) # Output: [10 30 50] (every 2nd element)
print(arr[5:0:-1]) # Output: [60 50 40 30 20] (reverse slice, skipping the first element)
For 2D arrays, you slice along each axis separated by a comma: arr[row_start:row_stop, col_start:col_stop]
arr2d = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print(arr2d[0:2, 1:3])
# Output:
# [[2 3]
# [6 7]]
Changes to a slice affect the original array since slicing returns a view, not a copy.
slice_arr = arr[1:4]
slice_arr[0] = 99
print(arr)
# Output: [10 99 30 40 50 60] (original array modified)
.copy()
:slice_copy = arr[1:4].copy()
slice_copy[0] = 100
print(arr) # Original unchanged
print(slice_copy) # Modified slice
You can use lists or arrays of indices to extract specific elements (not necessarily contiguous):
print(arr[[0, 2, 4]]) # Output: [10 30 50]
arr[start:stop]
: slice from start
to stop - 1
.arr[start:stop:step]
to skip elements.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!