IndexError: invalid index to scalar variable in Python 3.x

Dung Do Tien Mar 26 2022 93

I have a small block code with Python basic I practiced with the array using numpy package. I have created an array of 2 dimensions and I want to loop and print it. Like this

 import numpy as np

# Course
basic_courses = np.array([[1500,1],[3456,2],[333,3]])

for x in basic_courses:
  print(x[0][1])

But when running the code above I got an error IndexError: invalid index to scalar variable. I feel this block code is very basic but I don't understand this error.

 Traceback (most recent call last):
  File "main.py", line 12, in <module>
    print(x[0][1])
IndexError: invalid index to scalar variable.

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.
  • I

    IZDIHAR KHRIFECH Mar 26 2022

    You have trouble with the array in Python. the x variable is a 1D array NOT a 2D array. So you can fix it like as:

     import numpy as np
    
    # Course
    basic_courses = np.array([[1500,1],[3456,2],[333,3]])
    
    for x in basic_courses:
      print(x[0])

    #Output

     1500
    3456
    333

    I hope this answer is all you need.

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