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])
Output
Traceback (most recent call last):
File "c:ProjectsTryoutsPython Tutorial.py", line 8, in <module>
print(numbers[0,2])
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
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])
Output
The array element is 30
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))
Output
The array dimension is 1
The array dimension is 2
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
If you define an array and try to index it with more dimensions than the array has, you will raise the error: IndexError: too many indices for array. You need to recheck the array’s dimensions and index it with those dimensions to solve this error.
This tutorial will go through the error in detail and an example to learn how to solve it.
Table of contents
- IndexError: too many indices for array
- What is an IndexError?
- Indexing a Multidimensional Array Using Numpy
- Example: Indexing a 1-Dimensional Array
- Solution
- Summary
IndexError: too many indices for array
What is an IndexError?
Python’s IndexError occurs when the index specified does not lie in the range of indices in the bounds of a list. In Python, index numbers start from 0 and end at n-1, where n is the number of elements present in the list. Let’s look at an example of a Python array:
pets = ["cat", "dog", "hamster"]
This array contains three values, and the first element, cat, has an index value of 0. The second element, dog, has an index of 1. The third element, hamster, has an index of 2.
If we try to access an item at index position 3, we will raise an IndexError, because the list range is 0 to 2.
print(pets[3])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
1 print(pets[3])
IndexError: list index out of range
When accessing a list, remember that Python list indexing starts with 0.
Indexing a Multidimensional Array Using Numpy
To access elements in an n-dimensional array, we can use comma-separated integers representing the array’s dimension and index. Let’s look at an example with a two-dimensional array. We can think of a two-dimensional array as a table with rows and columns, and the row represents the dimension, and the index represents the column.
import numpy as np
arr = np.array([[2,3,4,5,6], [8, 4, 3, 2, 1]])
print('3rd element on 1st row: ', arr[0,2])
In the above code, the value 0 means we are accessing the first dimension or row, and the value 2 mean we are accessing the element in the third column of the first row. Let’s run the code to see the result:
3rd element on 1st row: 4
Example: Indexing a 1-Dimensional Array
Let’s look at an example where we define a numpy array in a single dimension and try to access the elements of the array in two dimensions.
import numpy as np
x = np.array([45, 12, 55, 99, 10, 5, 2])
print(x[0, 3])
Let’s run the code to get the output:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
3 x = np.array([45, 12, 55, 99, 10, 5, 2])
4
5 print(x[0, 3])
IndexError: too many indices for array
By using two numbers in square brackets separated by a comma [0, 3], we tell the Python interpreter to access the third element of the first array. However, there is only one array; therefore, we raise the IndexError.
Solution
To solve the error, you can use print statements to get the array’s shape and dimensions. Once you know the array’s dimensions, you must index using those dimensions. In this case, the array is one-dimensional; therefore, we only need to specify one index value. Let’s look at the revised code:
x = np.array([45, 12, 55, 99, 10, 5, 2])
print('Shape of the array is: ', np.shape(x))
print('Dimension of the array is: ', len(np.shape(x)))
print(x[0])
The function np.shape gives us the shape of the array. You can pass the numpy array shape to the len() function, returning the array’s dimension. Let’s run the code to see what happens:
Shape of the array is: (7,)
Dimension of the array is: 1
45
The code successfully runs and prints the element at the 0th index of the numpy array.
Summary
Congratulations on reading to the end of this tutorial! If you try to access an array using more dimensions than the array, you will raise the error: IndexError: too many indices for array. You can access multiple dimensions by adding commas between the index values. If you are accessing a one-dimensional array, you cannot index the array with two index values as if it were two-dimensional. To solve this error, first get the dimensions of your array by passing the shape of the array, using np.shape(array), to the len() function. Once you have the number of dimensions for the array you must index using those dimensions.
For further reading on IndexError, you can read the following articles:
- How to Solve Python IndexError: list index out of range
- How to Solve Python IndexError: single positional indexer is out-of-bounds
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Arrays in Python are one dimensional and two dimensional. Two-dimensional arrays consist of one or more arrays inside it. You can access the elements in a 2D array by mentioning two indices. The first index represents the position of the inner array. The other index represents the element within this inner array.
Python IndexError: too many indices for array
While using a numpy array, you might come across an error IndexError: too many indices for an array. This occurs when you are trying to access the elements of a one-dimensional numpy array as a 2D array. To avoid this error, you need to mention the correct dimensions of the array.
This error is thrown by Python ‘numpy array’ library when you try to access a single-dimensional array into multiple dimensional arrays.
Example
# Code with error
# Importing the numpy library
import numpy as np
# Declaring and Initializing the one Dimension Array
x = np.array([212,312,2,12,124,142,12])
# Printing the result
print(x[0,3])
OUTPUT:
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(x[0,3])
IndexError: too many indices
In the above example, we have declared a single dimensional array using numpy library array, but later in the code, we are trying to print it as a two-dimensional array.

Solution
To resolve this error, you have re-check the dimensions which you are using and the dimension you are declaring and initializing
# Code without errors
# Importing the numpy library
import numpy as np
# Declaring and initializing the one dimension array
x = np.array([212,312,2,12,124,142,12])
# To check the dimension of the array
print("Shape of the array = ",np.shape(x));
# Printing the result
print(x[0])
OUTPUT:
Shape of the array = (7,)
212
How to check the Dimension of Array
To check the dimension of your declared array use len(x.shape) function of the numpy library.
import numpy as np
myarray = np.array([[[2,4,4],[2,34,9]],[[12,3,4],[2,1,3]],[[2,2,2],[2,1,3]]])
print("Array Dimension = ",len(myarray.shape))
Output
Array Dimension = 3
Conclusion
The indices of the numpy array have to be mentioned according to the size. For a one dimensional array, mention one index. For 2D arrays, specify two indices. The best way to go about it is by using the len(myarray.shape).
for imagePath in paths.list_images(args[«image»]):
image = cv2.imread(imagePath)
img = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)
initialize OpenCV’s static fine grained saliency detector and
compute the saliency map
saliency = cv2.saliency.StaticSaliencyFineGrained_create()
(success, saliencyMap) = saliency.computeSaliency(image)
hist = desc.describe(saliencyMap)
orb = cv2.ORB_create(nfeatures=3000)
keypoints_orb, descriptors3 = orb.detectAndCompute(img, None)
des=descriptors3.reshape(-1)
des=des.astype(np.float32)
hist=np.concatenate((hist,des),axis=0)
res.append(hist)
dataset = np.array(res)
#Error is showing here IndexError: too many indices for array
X = dataset[400:2000,0:16]
y = np.array([np.ones(80) * 0, np.ones(80), np.ones(80) * 2, np.ones(80) * 3, np.ones(80) * 4, np.ones(80) * 5, np.ones(80) * 6, np.ones(80) * 7, np.ones(80) * 8, np.ones(80) * 9, np.ones(80) * 10, np.ones(80) * 11, np.ones(80) * 12, np.ones(80) * 13, np.ones(80) * 14, np.ones(80) * 15, np.ones(80) * 16, np.ones(80) * 17, np.ones(80) * 18, np.ones(80) * 19]).reshape(-1)
define the keras model
model = Sequential()
model.add(Dense(120, input_dim=16, activation=’relu’))
model.add(Dense(8, activation=’relu’))
model.add(Dense(20, activation=’softmax’))
compile the keras model
model.compile(loss=’sparse_categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])
fit the keras model on the dataset
model.fit(X, y, epochs=500, batch_size=10, verbose=1)
make class predictions with the model
predictions = model.predict_classes(dataset[0:400,0:16])
summarize the first 5 cases
y_test=np.array([np.ones(20) * 0, np.ones(20), np.ones(20) * 2, np.ones(20) * 3, np.ones(20) * 4, np.ones(20) * 5, np.ones(20) * 6, np.ones(20) * 7, np.ones(20) * 8, np.ones(20) * 9, np.ones(20) * 10, np.ones(20) * 11, np.ones(20) * 12, np.ones(20) * 13, np.ones(20) * 14, np.ones(20) * 15, np.ones(20) * 16, np.ones(20) * 17, np.ones(20) * 18, np.ones(20) * 19])
This is the code i am working. It extracts a histogram of image and descriptor for the image which describes about the keypoints in the image. The shape of histogram is <26,> and the shape of descriptor is <28120,> which differs based on the image. I am concatenating these two array and storing it in a list res. Then res is stored in dataset after extracting hist and descriptor for all images. The dataset is sent to x. Thats where the error is coming. I am using about 2000 images. 1-400 for testing and 401-2000 for training. please help me guys
To fix the “IndexError: too many indices for array” error in Python, there are two solutions we have effectively tested. Follow the article to better understand.
What causes the “IndexError: too many indices for array” error?
IndexError: An error occurs when you try to access an item in the list that is out of bounds.
Python arrays include one-dimensional arrays and two-dimensional arrays. A two-dimensional array consisting of one or more arrays within it. To access the 2D array, we will refer to two indices. The first index is the position of the array inside. The second index is the position of the element in that array.
The “IndexError: too many indices for array” error occurs when you access a one-dimensional array as 2D, so the following error occurs.
Example:
import numpy as np
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype = int)
print("myArray[1:2]=", myArray[1, 2])
Output:
Traceback (most recent call last):
File "prog.py", line 4, in <module>
print("myArray [1:2]=", myArray [1,2])
IndexError: too many indices for array
In the code above the error occurs when you declare a one-dimensional array but print it out as a two-dimensional array.
How to solve this error?
Check the dimension of the array you declared
Instead of declaring a one-dimensional array, you should declare a two-dimensional array and check its dimension.
Syntax:
array.shape
Example
import numpy as np
myArray = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
print("The dimension of arr", myArray.shape)
print("myArray[] =", myArray[:, 1])
Output:
The dimension of arr (4, 2)
myArray[] = [2 4 6 8]
After correctly defining the declared array as a 2D array consisting of 4 1-dimensional sub-arrays, each 1-dimensional sub-array consists of 2 elements.
The outputs will return the elements located in column 1 of the 2-dimensional array.
Check if the element in the subarray of the 2D array has the same size
Syntax:
len(name_array.shape)
Example:
import numpy as np
myArray = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
print("Element of the subarray :", len(myArray.shape))
print("myArray[] =", myArray[:, 1])
Output:
Element of the subarray : 2
myArray[] = [2 4 6 8]
After checking the number of elements in the subarray of the 2D array, you can be sure the subarrays are full of elements. Outputting the elements of a 2D array will not throw an error.
Note: Inhomogeneity in the size of the subarrays also causes the “IndexError: too many indices for array” error.
Summary
If you have any questions about the “IndexError: too many indices for array” error in python, leave a comment below. I will answer your questions.
Maybe you are interested:
- IndexError: index 0 is out of bounds for axis 0 with size 0
- IndexError: too many indices for array in Python
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java
Introduction
Another article where the main focus is to discuss on how ot handle the error message appear upon accessing the NumPy array elements. Basically, this error message appear upon the process of trial to access or to index the NumPy array element. The process for doing that is available in the previous article. It is an article with the title of ‘How to Access or to Index NumPy Array’ in this link. In order to use NumPy library and also define a NumPy array just take a look in the previous article to understand the setup. It is an article with the title of ‘How to Use NumPy’ in this link.
Basically, after getting NumPy library and also defining NumPy array, the process for accessing an element inside NumPy array trigger an error message as follows :
Microsoft Windows [Version 10.0.22000.856] (c) Microsoft Corporation. All rights reserved. C:UsersPersonal>python Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> numpy_array = np.array(1) >>> print(numpy_array[0]) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed >>>
Apparently, the solution for solving the above problem is very easy. It appears the trigger for the error message appear because of the false definition or declaration of the NumPy array itself. The following is the line which is defining or declaring the NumPy array :
>>> numpy_array = np.array(1)
Although it has an element which is become the parameter or the argument to declare or to define the NumPy array, the format is not suitable for further access. The above definition or declaration will only create a zero dimension NumPy array. It will cause the NumPy array to have no elements at all for further access. In that case, in order to access at least only one element from the NumPy array variable, just redeclare it with the correct format as follows :
>>> numpy_array = np.array([1])
It need to have a square bracket as an array definition to contain the element. So, after correcting the NumPy array declaration, it will handle the error message which is enabling to access and print the element as follows :
Microsoft Windows [Version 10.0.22000.856] (c) Microsoft Corporation. All rights reserved. C:UsersPersonal>python Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> numpy_array = np.array([1]) >>> print(numpy_array[0]) 1 >>>
Arrays or Lists and Tuples are contiguous data structures in Python. They can store elements belonging to a single data type and multiple data types together. For example, we can have a list or array or tuple that contains five integer elements, three floating-point numbers, seven class objects, two sets, and eight boolean values.
To access these elements, we can use the indexes of these elements. These data structures are 0-index based. Suppose we try to access an element at an index greater than or equal to the length of the data structure. In that case, we run into the IndexError exception.
In this article, we will learn how to fix this issue in Python.
How to Fix the too many indices for array error in Python
To fix the IndexError exception, one should make sure that they don’t enter an index equal to or greater than the length of the data structure.
The approach mentioned above is an obvious one. However, we can still write a stub or a utility function to grab a value from a list or tuple. This function will ensure we get the value at an index if it exists and safely handle invalid index values. Refer to the following Python code for the same.
def get_value(structure, index):
if not isinstance(index, int):
return None
if not isinstance(structure, (list, tuple)):
return None
if index >= len(structure):
return None
return structure[index]
a = ["Hello", "World", 1, 2.0, 3.00000, True, False]
print(get_value([], 4.0))
print(get_value(a, 4))
print(get_value(a, -1))
print(get_value(None, 8))
print(get_value("Hello World", "Python"))
Output:
Before returning the value at the specified index, the stub function above ensures that the index is of type int, the data structure is of type list or tuple, and the index is less than the length of the data structure. Once all the checks are passed, we can safely return the required value at the index.
One easier implementation of the get_value() function would be using the try and except block. Refer to the following Python code for the same.
def get_value(structure, index):
try:
return structure[index]
except:
return None
a = ["Hello", "World", 1, 2.0, 3.00000, True, False]
print(get_value([], 4.0))
print(get_value(a, 4))
print(get_value(a, -1))
print(get_value(None, 8))
print(get_value("Hello World", "Python"))
Output:
The try and except block would return None if anything goes wrong and an actual value if all the required conditions are successfully met.