NumPy Indexing & Slicing

Why indexing & slicing matter

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.

1D indexing & slicing

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)

2D indexing (rows, columns)

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]]

3D indexing (example)

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

Views vs Copies (important!)

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

Boolean indexing & where()

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]

Common patterns & pitfalls

  • Stop is exclusive: a[m:n] includes m but not n.
  • Negative indices: -1 is last element, -2 second last, etc.
  • Strides: a[start:stop:step]; reverse with step=-1.
  • Row vs column: In 2D, a[i] is a row; use a[:, j] for a column.
  • Views change the original: copy with .copy() when you need isolation.

Practice: quick exercises

# 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)
Numpy array() shape where() reshape() array_split()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate 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.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer