Python for Loop: Indexerror: List Index out of Range

Python for Loop: Indexerror: List Index out of Range

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.

2

4 Answers

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.

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

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

2

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 it’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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.