0
for i in range(len(a)):
    a = a[i-2]
    print(a)
IndexError: invalid index to scalar variable

So I am getting this index error, when i am trying to loop through my array. A is my array. I looked up the error invalid index to scalar variable online but it looks like its a case by case basis. Any help would be greatly appreciated. Ive tried replacing the for loop to this:

for i in range(len(a)):
    a = a(i-2)
    print(a)

But that doesn't work and throws up this error.

'numpy.ndarray' object is not callable

3 Answers 3

1

You should generally not attempt to change the variable you are looping over. Here you are looping over a and then changing a at each iteration of the loop.

This will work though

a = [1,2,3,4,5]

for i in range(len(a)):
    print(a[i-2])

You probably need to include an explanation of what it is you are trying to achieve so people can better help you.

Sign up to request clarification or add additional context in comments.

Comments

1

In addition to Eric's answer, you should be modifying the [i-2] part since that you'll end up trying to access an invalid element like a[-1]

Comments

1

Assuming a=[1,2,3,4], if you do

for i in range(len(a)):
 b = a[i]
 print(b)

should output

1
2
3
4

There were a two issues from what I could tell.

  1. you overwrite a after your first loop (a goes from array to scalar)
  2. you were using the indices (0,1,2,3) to ask for positions -2,-1, 0, 1 of the a array. Note the first two don't exist.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.