Skip to content

Array Indexing

Array Indexing

Elements in NumPy arrays can be accessed by indexing. Indexing is an operation that pulls out a select set of values from an array. The index of a value in an array is that value's location within the array. There is a difference between the value and where the value is stored in an array.

An array with 3 values is created in the code section below.

In [1]:
import numpy as np

a = np.array([2,4,6])

The array above contains three values: 2, 4 and 6. Each of these values has a different index.

Remember counting in Python starts at 0 and ends at n-1.

The value 2 has an index of 0. 2 is in the 0 location of the array. The value 4 has an index of 1 and the value 6 has an index of 2. The table below shows the index of each value in the array.

Index (or location) Value
0 2
1 4
2 6

Individual values stored in an array can be accessed with indexing.

The general form to index a NumPy array is:

<value> = <array>[index]

Where <value> is the value stored in the array, <array> is the array object name and [index] specifies the index or location of that value.

In the array above, the value 6 is stored at index 2.

In [1]:
import numpy as np

a = np.array([2,4,6]) value = a[2] print(value)


Multi-dimensional Array Indexing

Multi-dimensional arrays can be indexed as well. A simple 2-D array is defined by a list of lists.

In [3]:
import numpy as np

a = np.array([[2,3,4],[6,7,8]]) print(a)

[[2 3 4]
 [6 7 8]]

Values in a 2-D array can be accessed using the general notation below:

<value> = <array>[row,col]

Where <value> is the value pulled out of the 2-D array and [row,col] specifies the row and column index of the value. Remember Python counting starts at 0, so the first row is row zero and the first column is column zero.

We can access the value 8 in the array above by calling the row and column index [1,2] for the 2nd row (remember row 0 is the first row) and the 3rd column (remember column 0 is the first column).

In [4]:
import numpy as np

a = np.array([[2,3,4],[6,7,8]]) value = a[1,2] print(value)


Assigning Values with Indexing

Array indexing is used to access values in an array. And array indexing can also be used for assigning values of an array.

The general form used to assign a value to a particular index or location in an array is below:

<array>[index] = <value>

Where <value> is the new value going into the array and [index] is the location the new value will occupy.

The code below puts the value 10 into the second index or location of the array a.

In [5]:
import numpy as np
a = np.array([2,4,6])
a[2] = 10

[ 2  4 10]

Values can also be assigned to a particular location in a 2-D arrays using the form:

<array>[row,col] = <value>

The code example below shows the value 20 assigned to the 2nd column and 3rd row of the array.

In [6]:
import numpy as np

a = np.array([[2,3,4],[6,7,8]]) print(a)

a[1,2]=20 print(a)

[[2 3 4]
 [6 7 8]]
[[ 2  3  4]
 [ 6  7 20]]