logo

Using Tuples for Indexing in Python 📂Programing

Using Tuples for Indexing in Python

2D Arrays

Let’s call $A$ a 2D array. Then $A[(y,x)]$ and $A[y,x]$ perform the same function.

>>> import numpy as np
>>> A = np.arange(16).reshape(4,4)

>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

>>> A[2,3]
11
>>> A[(2,3)]
11
>>>

Using a tuple of tuples allows you to reference multiple specific indexes. It’s important to note that the first tuple within the tuple represents the index for the rows (the first dimension), and the second tuple represents the index for the columns (the second dimension). Therefore, if you want to insert 1, 2, 3 into the [0,0], [1,1], [2,2] positions of the array, instead of A[(0,0), (1,1), (2,2)] = [1, 2, 3], you should input it as A[(0, 1, 2), (0, 1, 2)] = [1, 2, 3].

>>> A = np.zeros((3,3))
>>> A
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

>>> A[(0,0), (1,1), (2,2)] = [1, 2, 3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

>>> A[(0, 1, 2), (0, 1, 2)] = [1, 2, 3]
>>> A
array([[1., 0., 0.],
       [0., 2., 0.],
       [0., 0., 3.]])

Multidimensional Arrays

For example, if you want to reference [0,0], [1,2], [2,3] from each 2D array in a multidimensional array, you should input it as follows.

>>> A = np.zeros((3,4,4))
>>> A
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])

>>> A[:, (0, 1, 2), (0, 2, 3)] = [1, 3, 9]
>>> A
array([[[1., 0., 0., 0.],
        [0., 0., 3., 0.],
        [0., 0., 0., 9.],
        [0., 0., 0., 0.]],

       [[1., 0., 0., 0.],
        [0., 0., 3., 0.],
        [0., 0., 0., 9.],
        [0., 0., 0., 0.]],

       [[1., 0., 0., 0.],
        [0., 0., 3., 0.],
        [0., 0., 0., 9.],
        [0., 0., 0., 0.]]])

Environment

  • OS: Windows10
  • Python 3.9.2, Numpy 1.19.5