Array Slicing and Indexing
Select individual elements, rows, columns, and sub-arrays using integer and slice notation on multi-dimensional arrays.
Integer Indexing in 1-D Arrays
A 1-D array is indexed just like a list: a[0] is first, a[-1] is last. Indexing returns a single scalar, and negative numbers count from the end.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10
print(a[-1]) # 50
print(a[2]) # 30Slicing 1-D Arrays
Slices use start:stop:step like lists, but a NumPy slice returns a view — no copy. Change the slice and you change the original, so use .copy() when needed.
import numpy as np
a = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
print(a[2:7]) # [2 3 4 5 6]
print(a[::2]) # [0 2 4 6 8]
print(a[::-1]) # [9 8 7 6 5 4 3 2 1 0]All lessons in this course
- Creating NumPy Arrays
- Array Attributes and Inspection
- Element-Wise Arithmetic
- Array Slicing and Indexing