Skip to content Skip to sidebar Skip to footer

How To Resolve Indexerror: List Assignment Index Out Of Range Using Array Inside Loop In Python

I'm new to python. I'm creating 2 arrays file_name(stores name of the files) and path(stores paths of files). Values of path array are assigned inside while loop. But I'm getting t

Solution 1:

You can't access path[count] and assign something to it if path[count] doesn't already exist.

To create a new list, use .append(). You don't need to keep track of a counter at all (it's rarely necessary to do a C-style loop in Python; the pythonic way is to iterate over the elements of a list/tuple/dictionary directly):

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []

for item in file_name:
    newpath = "D:\\Work\\" + item + ".csv"
    # or better: newpath = r"D:\Work\{}.csv".format(item)
    path.append(newpath)
    print(newpath)

Solution 2:

You are looking for the append method.

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []

count = 0while count < 9:
    path.append("D:\\Work\\"+file_name[count]+".csv")
    print (path[count])
    count = count + 1

You will get your expected output.

Solution 3:

You need to append an item to the list. It would look like that then:

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []

count = 0while count < 9:
    path.append("D:\\Work\\"+file_name[count]+".csv")
    print (path[count])
    count = count + 1

Since when you created an empty list, it had no items, thus accessing it via index didn't work. You can also skip the while loop and use some Python sugar to get the same effect:

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = ['D:\\Work\\' + x + '.csv'for x in file_name]
for p inpath:
    print(p)

Post a Comment for "How To Resolve Indexerror: List Assignment Index Out Of Range Using Array Inside Loop In Python"