How to resolve IndexError: list assignment index out of range using array inside loop in Python

两盒软妹~` 提交于 2019-12-25 09:40:07

问题


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 the error:

IndexError: list assignment index out of range in Python

I had already wasted several hours on this one, but haven't got the output as I expected. So, can you please let me know where I have made the mess? Any help will be highly appreciated. Thanks in advance.

My Code:

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

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

Expected Output:

D:\\Work\\abc.csv
D:\\Work\\xyz.csv
D:\\Work\\pqr.csv
D:\\Work\\mno.csv
D:\\Work\\def.csv
D:\\Work\\ghi.csv
D:\\Work\\rst.csv
D:\\Work\\uvw.csv
D:\\Work\\jkl.csv

回答1:


You are looking for the append method.

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

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

You will get your expected output.




回答2:


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)



回答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 = 0
while 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 in path:
    print(p)


来源:https://stackoverflow.com/questions/47409940/how-to-resolve-indexerror-list-assignment-index-out-of-range-using-array-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!