Arrays - indexing and slicing
NumPy - The Basics
1 min read
This section is 1 min read, full guide is 14 min read
Published Sep 22 2025
11
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
NumPyPython
- Indexing → access a single element using its position.
- Slicing → access a range of elements using
start:stop:step. - Supports multi-dimensional arrays -
[row, col]slicing for 2D or[depth, row, column]for 3D etc. - Negative indices count from the end (
-1is the last element). - Using
:selects the entire axis.
1D Array Examples:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
# Positive Indexing
print("arr[2] =", arr[2])
# → 30
# Negative Indexing
print("arr[-3] =", arr[-3])
# → 30
# Slicing start:stop
print("arr[1:4] =", arr[1:4])
# → [20 30 40]
print("arr[-4:-1] =", arr[-4:-1])
# → [20 30 40]
# Slicing with step
print("arr[0:5:2] =", arr[0:5:2])
# → [10 30 50]
print("arr[-5:-1:2] =", arr[-5:-1:2])
# → [10 30]
# From index to end
print("arr[2:] =", arr[2:])
# → [30 40 50]
print("arr[-3:] =", arr[-3:])
# → [30 40 50]
# From start to index
print("arr[:3] =", arr[:3])
# → [10 20 30]
print("arr[:-2] =", arr[:-2])
# → [10 20 30]
Copy to Clipboard
Toggle show comments
2D Array Examples:
arr2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Single element
print("arr2d[1,2] =", arr2d[1,2])
# → 6
print("arr2d[-2,-1] =", arr2d[-2,-1])
# → 6
# Row slicing
print("arr2d[1,:] =", arr2d[1,:])
# → [4 5 6]
print("arr2d[-2,:] =", arr2d[-2,:])
# → [4 5 6]
# Column slicing
print("arr2d[:,2] =", arr2d[:,2])
# → [3 6 9]
print("arr2d[:,-1] =", arr2d[:,-1])
# → [3 6 9]
# Subarray
print("arr2d[0:2,1:3] =", arr2d[0:2,1:3])
# → [[2 3]
# [5 6]]
print("arr2d[-3:-1,-2:] =", arr2d[-3:-1,-2:])
# → [[2 3]
# [5 6]]
# Step in slicing
print("arr2d[::2,::2] =", arr2d[::2,::2])
# → [[1 3]
# [7 9]]
Copy to Clipboard
Toggle show comments
3D Array Examples:
import numpy as np
arr3d = np.array([
[[ 1, 2, 3], [ 4, 5, 6]],
[[ 7, 8, 9], [10, 11, 12]],
[[13, 14, 15], [16, 17, 18]]
])
# Accessing a single element
print("Element at depth 1, row 0, col 2:", arr3d[1,0,2])
# → 9
print("Element with negative indexing:", arr3d[-2,0,-1])
# → 9
# Accessing a whole “layer” (2D slice)
print("Layer 0:\n", arr3d[0])
# → [[1 2 3]
# [4 5 6]]
print("Last layer with negative indexing:\n", arr3d[-1])
# → [[13 14 15]
# [16 17 18]]
# Accessing a row across layers
print("First row across all layers:\n", arr3d[:,0,:])
# → [[ 1 2 3]
# [ 7 8 9]
# [13 14 15]]
# Accessing a column across layers
print("Second column across all layers:\n", arr3d[:,:,1])
# → [[ 2 5]
# [ 8 11]
# [14 17]]
# Subarray / slicing with steps
print("Every other layer, all rows, last two columns:\n", arr3d[::2, :, 1:])
# → [[[ 2 3]
# [ 5 6]]
# [[14 15]
# [17 18]]]
Copy to Clipboard
Toggle show comments














