Home > Enterprise >  Python for loop: IndexError: list index out of range
Python for loop: IndexError: list index out of range

Time:02-15

I am new with Python, This is my code:

import numpy as np

x = [0, 0, 0, 0, 5, 0, 10, 5]
y = [4, 4, 4, 4, 9, 4, 2, 9]

def unitvector1 (x,y):
    looplim=(len(x) 1)

    for i in range (0,looplim):
        z=i 1
        alfa = np.arccos((x[i]*x[z]) (y[i]*y[z])) / ((np.sqrt(x[i] ^ 2 y[i] ^ 2) * np.sqrt(x[z] ^ 2 y[z] ^ 2))) 

        beta =  (180-alfa)

    return (beta)

temp=unitvector1(x,y)

print(temp)

And I am getting this error:

IndexError: list index out of range

I tried to do it with two for loops but it did not work.

Your help is much needed, Many thanks in advance for your help.

CodePudding user response:

Lists are indexed starting from 0, so for a list of length, say, 13, the last valid index is 12, i.e., 1 less than the length.

When you do looplim=(len(x) 1) and then for i in range (0,looplim), the last value of i is looplim-1 which is equal to len(x), so it's the length rather than 1 less than that.

CodePudding user response:

looplim=len(x) 
for i in range(looplim-1):
alfa = np.arccos((x[i]*x[z]) (y[i]*y[z])) / ((np.sqrt(x[i] ^ 2 y[i] ^ 2) * 
np.sqrt(x[z] ^ 2 y[z] ^ 2)))  

for each iteration value of "alfa" is nan

CodePudding user response:

remove 1 from looplim=(len(x) 1) and z = i 1 then run the code !

CodePudding user response:

Okay, first u should look at your variable z. When i=7 z=8 and there are no eight’s index element in x array. Second, idk why you try “looplim”. If you want to do operations with n and n 1 elements in this way we can add next:

   def unitvector1 (x,y):
      for i in range (len(x)-1):
          z=i 1
          if z==len(x) 1:
              z=0
          alfa = np.arccos((x[i]*x[z]) (y[i]*y[z])) / ((np.sqrt(x[i] ^ 2 y[i] ^ 2) * np.sqrt(x[z] ^ 2 y[z] ^ 2))) 

          beta =  (180-alfa)

    return (beta)

But there’s not working! Because arccos(alpha) should have alpha<|1|

If you can explain what do you want to count, maybe we can help you

CodePudding user response:

Several things:

  • To do exponentiation in Python, you should use the ** operator instead of ^.
  • You are asking to return a variable ("beta") which you have not declared previously.
  • Also, you are using the operator "= " which I believe should be " =".
  • Furthermore, you are incrementing z by a rate of " 1" every loop. Thus, when you are beyond len(x), you will not be able to access/call x[z] (because that index does not exist in your x list).
  • Related