Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 8 of 60 · python

Indexing, Slicing, and Iterating in NumPy

Duration: 20 minutes

Indexing, Slicing, and Iterating

NumPy provides powerful ways to access sub‑arrays.

1‑D indexing

arr = np.arange(10)
print(arr[3])      # 3
print(arr[-1])     # 9

2‑D slicing

mat = np.arange(1, 13).reshape(3,4)
print(mat)
# Slice rows 0‑1 and columns 1‑3
sub = mat[0:2, 1:4]
print(sub)

Boolean indexing

mask = arr % 2 == 0   # even numbers mask
print(arr[mask])      # [0 2 4 6 8]

Fancy indexing

rows = np.array([0,2])
cols = np.array([1,3])
print(mat[rows, cols])   # [2 12]

Iterating (avoid when possible)

for row in mat:
    print(row)

Performance note: Vectorized operations are much faster than Python loops.

Warning

Do not mix integer and boolean indexing in the same operation, as it leads to confusing results.

Previous: NumPy Arrays and Data TypesNext: Broadcasting in NumPy