How to Solve Error Message IndexError: index 1 is out of bounds for axis 0 with size 1 when accessing NumPy array elements

Posted on

Introduction

An article where the focus is just to solve an error message. The error message has a relation with several previous articles. The first one is the article presenting how to use a NumPy library exist in this link. Another one is the article where the one showing how to access the NumPy array element. It is an article with the title of ‘How to Access or Index NumPy Array’ in this link. In the process of accessing the NumPy array element, there is an error message appear as exist below :

Microsoft Windows [Version 10.0.22000.856]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Personal>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[1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 1 is out of bounds for axis 0 with size 1
>>>

How to Solve Error Message IndexError: index 1 is out of bounds for axis 0 with size 1

So, in this part the focus is about to try to handle error message as in the discussion exist in the previous part. Actually, it is very easy to handle this kind of error. As the indexing rule for the NumPy array variable, the trigger is because this rule is being violated. The main indexing rule is that for accessing the first element, it have to use the index number of 0. Since the NumPy array variable only have one element, accessing it with index number 1 will violate the rule. In the end, it will trigger the error message. In order to fix this error, the simple solution is just to access with the correct index. It is by accessing it using the following format :

Microsoft Windows [Version 10.0.22000.856]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Personal>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
>>>

Leave a Reply