DEV Community

Srinivas for ItsMyCode

Posted on • Originally published at itsmycode.com on

IndexError: too many indices for array

ItsMyCode |

The indexerror: too many indices for an array means that you have a declared an array in a different dimension and trying to index it in another dimension.

For example, suppose you have declared a numpy array in a single dimension and try to access the elements of an array in 2 dimensional. In that case, you will get too many indices for array error, as shown below.

# Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
numbers = np.array([10,20,30,40,50])

# Indexing and accessing array as 2D causes IndexError
print(numbers[0,2])
Enter fullscreen mode Exit fullscreen mode

Output

Traceback (most recent call last):
  File "c:\Projects\Tryouts\Python Tutorial.py", line 8, in <module>
    print(numbers[0,2])
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
Enter fullscreen mode Exit fullscreen mode

The above code is a classic example of indexerror: too many indices for an array. We have declared a single dimensional array in the code, but on the other hand, we are trying to print the array as a two-dimensional array.

How to fix indexerror: too many indices for array

The resolution is pretty simple, where you need to make sure to re-check the dimension of an array you have declared and trying to index or access it in the same way.

# Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
numbers = np.array([10,20,30,40,50])

# Indexing and accessing array correctly
print("The array element is ",numbers[2])
Enter fullscreen mode Exit fullscreen mode

Output

The array element is 30
Enter fullscreen mode Exit fullscreen mode

How to Check the dimension of a numpy array in Python?

If it’s a dynamic numpy array, you could also check the dimension of an array using the len()method, as shown below.

You can pass the numpy array shape to the len() function and return the array’s dimension.

# Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
numbers1d = np.array([10,20,30,40,50])

# Declaring and Initializing the one Dimension Array
numbers2d = np.array([[[10,1],[20,2],[30,3],[40.4],[50.5]]])

print("The array dimension is ", len(numbers1d.shape))
print("The array dimension is ", len(numbers2d.shape))
Enter fullscreen mode Exit fullscreen mode

Output

The array dimension is 1
The array dimension is 2
Enter fullscreen mode Exit fullscreen mode

The post IndexError: too many indices for array appeared first on ItsMyCode.

Discussion (0)