Search code examples
pythonindex-error

Python IndexError: list assignment index out of range


I am getting this error due to the total_distance[counter4] = sum(d) line. I do not know what is causing it, I have appended values to d and am simply summing them and assigning that value to an index in an array. What is causing this error?

total_distance= []
d=[]
all_city = []
lowest_distance = 0

for permutation in itertools.permutations(city,len(city)):
   all_city.append(permutation)

for l in all_city:
    z = []
    q = 0
    counter4 = 0
    while q < len(city):
        z.append(int(l[q]))
        q = q+1
    for m in z:
        n = m - 1
        first_index = 0
        counter1 = 0
        if counter < len(z):
            checktime(initial_time1,time_limit1,total_distance)
            if counter1 == 0:
                first_index = n

            d.append(math.sqrt(math.pow((int(float(x[n + 1])) - int(float(x[n]))), 2) + math.pow((int(float((y[n + 1]))) - int(float(y[n]))), 2)))

        elif counter1 == len(z):
            checktime(initial_time1, time_limit1,total_distance)
            d.append(math.sqrt(math.pow((int(float(x[n]))-int(float(x[first_index]))), 2)+math.pow((int(float(y[n]))-int(float(y[first_index]))),2)))

        counter1 = counter1 + 1

    total_distance[counter4] = sum(d) # ERROR LINE
    counter4 = counter4 + 1

Solution

  • Use 'append' to add values to empty list. As you did it before.

    total_distance.append(sum(d))