Last updated

Array Indexing

Definition: Indexing means reading a single element by its position. Like Python lists, NumPy positions start at 0. In a 2D array you give [row, column].

Example 1 — 1D array

import numpy as np
a = np.array([10, 20, 30, 40])
print(a[0])    # 10 (first)
print(a[2])    # 30
print(a[-1])   # 40 (last)

Example 2 — 2D array

import numpy as np
b = np.array([[1, 2, 3],
              [4, 5, 6]])
print(b[0, 2])   # row 0, col 2 -> 3
print(b[1, 0])   # row 1, col 0 -> 4

Changing a value

import numpy as np
a = np.array([10, 20, 30])
a[1] = 99
print(a)   # [10 99 30]

💡 Tip: the comma form b[1, 0] is the NumPy way to index 2D arrays — cleaner than b[1][0].

Try it Yourself
Output

          
Ad · responsive