IndexError: index 1 is out of bounds for axis 0 with size 1

Dung Do Tien Mar 26 2022 657

Hello Guys, I'm just studying Python two days before and I practiced with the array using NumPy package.
I have created an array of 3 dimensions and I want to get some items on it. Like this

# Import the numpy library
import numpy as np

# Declaring and Initializing the block 3D Dimension Array
blocks = np.array([[[10,1],[20,2],[30,3],[40,4],[50,5]]])

#print first block here
print(blocks[1][1])

But when running the code above I got an error IndexError: index 1 is out of bounds for axis 0 with size 1. I feel this block code is very basic but I don't understand this error.

Traceback (most recent call last):
  File "HelloWorld.py", line 8, in <module>
    print(blocks[1][1])
IndexError: index 1 is out of bounds for axis 0 with size 1

I'm using Python 3.9.9 and running on Windows 11 64bit.

Do you have any suggestions for me?

Thank you so much.

Have 1 answer(s) found.
  • m

    mohammad faizan Mar 26 2022

    Oh, I think you still don't know a theory very basic about an array, that is the index of an array is always from 0, not 1.

    [[[10,1],[20,2],[30,3],[40,4],[50,5]]]

    You can see, your array has 3 dimensions and has only one item. So you have to access from 0. You can see the demo below:

    print(blocks[0][1]) # Print [20 2]
    print(blocks[0][1][0]) # Print 20
    print(blocks[0][0][1]) # Print 1
    print(blocks[0]) # Print [[10,1],[20,2],[30,3],[40,4],[50,5]]

    I hope, this answer is useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close