NumPy Indexing & Slicing

Access elements, rows and columns.

✍️ 3 exercises + code challenge in this lesson
  • 1-D: arr[0], arr[-1], slice arr[1:4], step arr[::2]
  • 2-D: m[row, col], a whole row m[0], a whole column m[:, 1]
A slice is a view: changing it changes the original array. Use .copy() for an independent copy.

Key Takeaways: NumPy Indexing & Slicing

Mastering NumPy Indexing & Slicing helps you write clean and reliable NumPy code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

NumPy Indexing & Slicing Code Example

NumPy
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[0], arr[-1])
print(arr[1:4])
print(arr[::2])

m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(m[1, 2])
print(m[:, 0])
Output
10 50
[20 30 40]
[10 30 50]
6
[1 4 7]
Free sign-in required · Google login available

NumPy Indexing & Slicing Practice Exercises

Check what you learned in “NumPy Indexing & Slicing”.

/ 3 solved
Fill in the blank

Select the whole second column of a 2-D array.

col = m[:, ]
✓ Correct! Not quite. Try again.
Multiple choice

What is a NumPy slice?

✓ Correct! Not quite. Try again.
Code challenge

Print the last element of arr using a negative index.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services