Indexing and slicing let you access and transform subsets of data without loops. Most slices return views (no copy), making them fast and memory-efficient.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10 (first element)
print(a[-1]) # 50 (last element)
# slice: start:stop (stop is exclusive)
print(a[1:4]) # [20 30 40]
print(a[:3]) # [10 20 30]
print(a[3:]) # [40 50]
# step / stride
print(a[::2]) # [10 30 50]
print(a[::-1]) # [50 40 30 20 10] (reverse)
b = np.array([[ 1, 2, 3],
[10, 20, 30],
[40, 50, 60]])
print(b[0, 1]) # 2 (row 0, col 1)
print(b[1]) # [10 20 30] (row 1)
print(b[:, 0]) # [ 1 10 40] (first column)
# Sub-matrix: rows 0..1, cols 1..2
print(b[0:2, 1:3]) # [[ 2 3],
# [20 30]]
# Every row, every other col
print(b[:, ::2]) # [[ 1 3],
# [10 30],
# [40 60]]
c = np.arange(2*3*4).reshape(2,3,4) # shape (depth=2, rows=3, cols=4)
# Pick depth=1, rows 0..1, cols 2..3
print(c[1, 0:2, 2:4])
# Ellipsis to keep all middle dims:
print(c[..., 0]) # first column from each 2D slice
a = np.array([0, 1, 2, 3, 4, 5])
s = a[1:4] # slice -> view (shares memory)
s[0] = 99
print(a) # [ 0 99 2 3 4 5] (a changed!)
# Force a copy if you need independence:
s_copy = a[1:4].copy()
s_copy[0] = -1
print(a[1:4]) # original remains unchanged now
Use boolean masks to filter arrays. np.where
builds masks or chooses values conditionally.
x = np.array([5, 12, 7, 22, 3, 18])
mask = x >= 10
print(mask) # [False True False True False True]
print(x[mask]) # [12 22 18]
# Conditional replace: values < 10 become 0
y = np.where(x < 10, 0, x)
print(y) # [ 0 12 0 22 0 18]
a[m:n]
includes m
but not n
.-1
is last element, -2
second last, etc.a[start:stop:step]
; reverse with step=-1
.a[i]
is a row; use a[:, j]
for a column..copy()
when you need isolation.# 1) Extract every 3rd element from 0..29 starting at 2
a = np.arange(30)
print(a[2::3])
# 2) From a 6x6 array, get the 3x3 center block
b = np.arange(36).reshape(6,6)
print(b[1:4, 1:4])
# 3) Replace all odd numbers in 0..19 with -1 using boolean mask
c = np.arange(20)
c[c % 2 == 1] = -1
print(c)
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.