Python Forum

Full Version: IndexError: list assignment index out of range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This seems to be something that a lot of new people to python seem to struggle with, and I'm no exception....

I understand that appending the values is something I need to do, but.. I'm obviously not doing it QUITE right..

This is my code:
x=0
dist=[]
while x < 100:
dist.append(x)
dist[x]=400/(math.cos(angle))
print (dist[x])
x = x+1
Where angle comes from earlier in the code. But I still get the list assignment out of range error. What am I doing wrong?
Hi,

I don't get that error because indentation is missing from the code, math has not been imported and angle has not been defined. when asking questions please show code that can be run, that will give the error, also please post the full error trace back in error tags.

For what you seem to be doing a for loop would be easier
import math

angle = 20

dist=[]

for x in range(100):
    calculation = 400/(math.cos(angle))
    dist.append(calculation)
    print(calculation)
i assume the value of x is supposed to be in the calculation somewhere, because it currently just outputs
Output:
980.1950083826823
100 times.
Brilliant thank you.

Apologies, there was a long code beforehand which gives the angle value, which I knew to be working, so didn't include.

So, if I am to understand correctly, the append function adds another value to the list (in this case dist), which is the value in the brackets. Now makes sense.
Yes it is appending calculation to the end of the sequence.
my_list = []
print(my_list)
my_list.append('an item')
print(my_list)
my_list.append('another item')
print(my_list)
Output:
[] ['an item'] ['an item', 'another item']