- 1-D:
arr[0],arr[-1], slicearr[1:4], steparr[::2] - 2-D:
m[row, col], a whole rowm[0], a whole columnm[:, 1]
A slice is a view: changing it changes the original array. Use
.copy() for an independent copy.Access elements, rows and columns.
✍️ 3 exercises + code challenge in this lessonarr[0], arr[-1], slice arr[1:4], step arr[::2]m[row, col], a whole row m[0], a whole column m[:, 1].copy() for an independent copy.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.
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])
10 50 [20 30 40] [10 30 50] 6 [1 4 7]
Check what you learned in “NumPy Indexing & Slicing”.
Select the whole second column of a 2-D array.
col = m[:, ]
What is a NumPy slice?
Print the last element of arr using a negative index.
Free sign-in required · Google login available
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