Understanding Slicing in NumPy (1D to 3D)
When working with arrays in NumPy, slicing allows you to access and manipulate portions of data. It's like zooming into your array with precision, whether it's a simple line of numbers or a cube of values.
What is Slicing?
Slicing means extracting a subset of values from an array by specifying a range of indices. The basic syntax is:
array[start:stop:step]
This works for all dimensions, with each dimension separated by a comma in multi-dimensional arrays.
1D Array Slicing
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70])
print("Original Array:", arr)
# Slicing from index 1 to 4
print("arr[1:5] =", arr[1:5])
# Slicing with step
print("arr[::2] =", arr[::2])
# Negative indexing
print("arr[-4:-1] =", arr[-4:-1])
Original Array: [10 20 30 40 50 60 70]
arr[1:5] = [20 30 40 50]
arr[::2] = [10 30 50 70]
arr[-4:-1] = [40 50 60]
Explanation:
arr[1:5]
gives elements from index 1 to 4 (stop index is exclusive).arr[::2]
returns every second element.arr[-4:-1]
uses negative indices to slice from the end of the array.
2D Array Slicing
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
# Slice entire second row
print("matrix[1, :] =", matrix[1, :])
# Slice first column
print("matrix[:, 0] =", matrix[:, 0])
# Slice 2x2 submatrix
print("matrix[0:2, 1:3] =\n", matrix[0:2, 1:3])
matrix[1, :] = [4 5 6]
matrix[:, 0] = [1 4 7]
matrix[0:2, 1:3] =
[[2 3]
[5 6]]
Explanation:
matrix[1, :]
gets all columns in the second row.matrix[:, 0]
fetches all rows in the first column.matrix[0:2, 1:3]
gives a 2x2 submatrix from top right.
3D Array Slicing
tensor = np.array([
[[ 1, 2], [ 3, 4]],
[[ 5, 6], [ 7, 8]],
[[ 9, 10], [11, 12]]
])
# Extract first 2D block
print("tensor[0] =\n", tensor[0])
# Slice specific element
print("tensor[1, 0, 1] =", tensor[1, 0, 1])
# Slice across blocks
print("tensor[:, 1, :] =\n", tensor[:, 1, :])
tensor[0] =
[[1 2]
[3 4]]
tensor[1, 0, 1] = 6
tensor[:, 1, :] =
[[ 3 4]
[ 7 8]
[11 12]]
Explanation:
tensor[0]
extracts the first 2D slice (like a sheet from a cube).tensor[1, 0, 1]
dives into block 1, row 0, column 1.tensor[:, 1, :]
selects all blocks, second row in each, all columns.
Best Practices & Checks
- Remember that slicing never raises an IndexError — out-of-bound indices are handled gracefully by NumPy.
- Slicing returns a view (not a copy) — modifying it may alter the original array.
- Use
copy()
if you need a separate duplicate.
Verify Your Understanding
# What does this return?
arr = np.array([[10, 20, 30], [40, 50, 60]])
print(arr[:, 1:])
Answer: It returns the second and third columns from all rows:
[[20 30]
[50 60]]
Conclusion
Slicing helps you work efficiently with subsets of data — whether you're analyzing rows, cropping image arrays, or preparing input for a neural network. Start practicing with simple slices and scale up to 3D — you'll build that muscle of array intuition step by step.