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, updated Aug 17 2026
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 nparr = np.array([10, 20, 30, 40, 50])# Positive Indexingprint("arr[2] =", arr[2]) # → 30# Negative Indexingprint("arr[-3] =", arr[-3]) # → 30# Slicing start:stopprint("arr[1:4] =", arr[1:4]) # → [20 30 40]print("arr[-4:-1] =", arr[-4:-1]) # → [20 30 40]# Slicing with stepprint("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 endprint("arr[2:] =", arr[2:]) # → [30 40 50]print("arr[-3:] =", arr[-3:]) # → [30 40 50]# From start to indexprint("arr[:3] =", arr[:3]) # → [10 20 30]print("arr[:-2] =", arr[:-2]) # → [10 20 30]2D Array Examples:
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])# Single element print("arr2d[1,2] =", arr2d[1,2]) # → 6print("arr2d[-2,-1] =", arr2d[-2,-1]) # → 6# Row slicingprint("arr2d[1,:] =", arr2d[1,:]) # → [4 5 6]print("arr2d[-2,:] =", arr2d[-2,:]) # → [4 5 6]# Column slicingprint("arr2d[:,2] =", arr2d[:,2]) # → [3 6 9]print("arr2d[:,-1] =", arr2d[:,-1]) # → [3 6 9]# Subarrayprint("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 slicingprint("arr2d[::2,::2] =", arr2d[::2,::2]) # → [[1 3]# [7 9]]3D Array Examples:
import numpy as nparr3d = np.array([ [[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]] ])# Accessing a single elementprint("Element at depth 1, row 0, col 2:", arr3d[1,0,2]) # → 9print("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 layersprint("First row across all layers:\n", arr3d[:,0,:])# → [[ 1 2 3]# [ 7 8 9]# [13 14 15]]# Accessing a column across layersprint("Second column across all layers:\n", arr3d[:,:,1])# → [[ 2 5]# [ 8 11]# [14 17]]# Subarray / slicing with stepsprint("Every other layer, all rows, last two columns:\n", arr3d[::2, :, 1:])# → [[[ 2 3]# [ 5 6]]# [[14 15]# [17 18]]]