Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 19 of 25

Indexing and slicing

A 1D array is indexed just like a list: a[0] is the first element, a[-1] the last, and a[1:4] a slice.

A 2D array takes one index per dimension, separated by a comma: m[row, column]. Both start at 0.

m = np.array([[10, 20, 30],
              [40, 50, 60]])
print(m[1, 2])    # 60
print(m[0])       # first row: [10 20 30]
print(m[:, 1])    # second column: [20 50]

A colon on its own means "everything along this dimension", so m[:, 1] reads as "all rows, column 1". Slices combine to cut out a block: m[0:2, 1:3] is rows 0 and 1, columns 1 and 2.

You can also pick several positions at once by passing a list of indexes, for example a[[0, 2, 5]]. This is called fancy indexing.

Indexing also works on the left of =, which changes values in place: m[0, 0] = 99 changes one element, and m[:, 1] = 0 sets a whole column.

One difference from real NumPy: in a full installation, a slice shares memory with the original array, so changing the slice changes the original too. This practice version always copies. Write .copy() whenever you want an independent copy, and your code will behave the same in both.

Key takeaways

  • A 1D array is indexed like a list. A 2D array takes one index per dimension: m[row, column].
  • A colon means everything along that dimension, so m[:, 1] is all rows of column 1.
  • Slices combine to cut out a block: m[0:2, 1:3] is rows 0 and 1 and columns 1 and 2.
  • Indexing on the left of = changes values in place.

Common mistakes

  • Using an index past the end of a dimension, such as m[3, 0] in an array with three rows. Read the IndexError guide.
  • Forgetting that positions start at 0, so the first row is m[0].

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.