user13131839
user13131839

Reputation: 11

How to loop through an array

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

Upvotes: 0

Views: 57

Answers (3)

Matt
Matt

Reputation: 186

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.

Upvotes: 1

user3842413
user3842413

Reputation: 176

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]

Upvotes: 1

Eric M
Eric M

Reputation: 1418

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.

Upvotes: 1

Related Questions