IndexError: too many indices for array

What is IndexError?

An IndexError is an error that occurs when an application tries to access an element of a list, but the list does not contain any elements with that index. We often use arrays in programming, There are dimensions in an array that we call 1D array, 2D array, and 3D array. Sometimes we make a single dimension array and try to access it like a two-dimension array so that time the error appears is “IndexError: too many indices for array”.

Example

# Import the numpy library

import numpy as np

# Declaring Single Dimension Array

numbers = np.array([5,8,13,20,33])

# Trying to accessing array as two-dimension causes IndexError

print(numbers[0,3])

Output

Traceback :
  File "E:\Python\array-dimensions.py", line 11 , in <module>
    print(numbers[0,3])
IndexError: too many indices for array

This is a simple example first, we imported the NumPy Library then
we defined a single dimension array (1-D) but we are trying to print it as a /two-dimension array(2-D).

How to fix python index error?

fixing it is very easy, you have to just remove 0 from the last line of code.

Solution of indexerror: too many indices for array

# Import the numpy library

import numpy as np

# Declaring Single Dimension Array

numbers = np.array([5,8,13,20,33])

# Accessing single dimesion array

print(numbers[3])

Output

 30

we saw that we just remove the index as the second dimension and it works but sometimes newbies get confused about whether it’s a single dimension array or two-dimension array so for this we have to find the dimensions of an array.

How to check the dimension of a NumPy array in Python?

There is one pre-defined function in python called len() and an attribute called shape. it’s used to find the length of an array, string, and somehow array dimensions as well.

Example

# Import the numpy library

import numpy as np

# Declaring The Single Dimension Array
array1 = np.array([5,8,13,20,33])

# Declaring The Two Dimension Array
array2    = np.array([[4, 9], [6, 27], [54, 98], [102, 119]])

print("Dimension of array1 is ", len(array1.shape))

print("Dimension of array2 is ", len(array2.shape))

Output

Dimension of array1 is  1
Dimension of array2 is  2

Conclusion

We solved the most common issue for newbies in python programming. In this article, we defined the best and easy way to solve it you can try these examples in any code editor.

Leave a Comment